From 9a6c81114a60e1cfcf467fcc9a59a6cedde5253f Mon Sep 17 00:00:00 2001 From: Joey <17398284+josephfarina@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:40:39 -0800 Subject: [PATCH 1/4] fix(cli): template's outside-the-project refusal names the command that writes the path from its own folder --- .changeset/template-refusal-cd-hint.md | 7 ++ packages/cli/api/template/copy/copy.mjs | 49 +++++++++++- .../commands/template.path-safety.test.mjs | 80 +++++++++++++++++++ packages/cli/clients/cli/lib/cli-error.mjs | 23 +++++- .../cli/clients/cli/lib/cli-error.test.mjs | 23 ++++++ 5 files changed, 175 insertions(+), 7 deletions(-) create mode 100644 .changeset/template-refusal-cd-hint.md diff --git a/.changeset/template-refusal-cd-hint.md b/.changeset/template-refusal-cd-hint.md new file mode 100644 index 0000000000000..9d6e27eb80560 --- /dev/null +++ b/.changeset/template-refusal-cd-hint.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[fix] When `astryx template ` refuses a path outside the project, it also names the command that writes that same path: a change to the nearest folder of it that exists, then the template command with the path from there. Printed, the CLI invocation follows the change of folder. + +@josephfarina diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs index cd3cf226cc024..2e5ce019d084d 100644 --- a/packages/cli/api/template/copy/copy.mjs +++ b/packages/cli/api/template/copy/copy.mjs @@ -28,7 +28,10 @@ import { } from '../../../foundation/discovery/template-adapter.mjs'; import {analyzeTemplateNeeds} from '../../../foundation/discovery/template-needs.mjs'; import {templateDestination} from '../../../foundation/discovery/template-destination.mjs'; -import {quoteCommandArgument} from '../../../foundation/env/package-manager.mjs'; +import { + commandInFolder, + quoteCommandArgument, +} from '../../../foundation/env/package-manager.mjs'; import { NO_ICON_SETS, mapTemplateIcons, @@ -104,10 +107,11 @@ export function templateCopy( scratch = true; } else if (outsideProject) { // Outside the project and the temp folder there is nothing to write, - // so the refusal names a place inside the project and the print that - // writes nothing. + // so the refusal names a place inside the project, the same path run + // from its own folder, and the print that writes nothing. const folder = templateDestination(cwd, match.type, match.dirName); const [scratchFolder] = tempFolders(); + const there = fromNearestFolder(targetPath); throw new AstryxError( `Invalid template target path "${given}": it is outside the project root (${path.resolve(cwd)}). ` + (scratchFolder @@ -118,6 +122,17 @@ export function templateCopy( name: `${command} ${quoteCommandArgument(folder)}`, reason: `write the ${match.type} inside the project`, }, + ...(there + ? [ + { + name: commandInFolder( + there.dir, + `${command} ${quoteCommandArgument(there.path)}`, + ), + reason: `write the ${match.type} where you named it, from its folder`, + }, + ] + : []), {name: command, reason: 'print the source and write nothing'}, ], ERROR_CODES.ERR_PATH_TRAVERSAL, @@ -227,3 +242,31 @@ function inTempFolder(file, given, temp) { ); } } + +/** + * Where a command run from another folder writes `target`: the nearest folder + * of it that exists, and the path from there. From that folder the path is + * inside the current folder, so the copy writes it there. Null when only the + * disk's root exists, which is no place to run a project command from. + * @param {string} target the destination as named, absolute + * @returns {{dir: string, path: string} | null} + */ +function fromNearestFolder(target) { + let dir = path.dirname(target); + while (!isFolder(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir); + if (path.dirname(dir) === dir) return null; + const rel = path.relative(dir, target).split(path.sep).join('/'); + return {dir, path: `./${rel}`}; +} + +/** + * @param {string} dir + * @returns {boolean} + */ +function isFolder(dir) { + try { + return fs.statSync(dir).isDirectory(); + } catch { + return false; + } +} diff --git a/packages/cli/clients/cli/commands/template.path-safety.test.mjs b/packages/cli/clients/cli/commands/template.path-safety.test.mjs index a3f8b23e943dd..e22cb9cf0cb88 100644 --- a/packages/cli/clients/cli/commands/template.path-safety.test.mjs +++ b/packages/cli/clients/cli/commands/template.path-safety.test.mjs @@ -135,6 +135,58 @@ describe('template path safety', () => { }, ); + it.skipIf(process.platform === 'win32')( + 'names the same path run from its nearest folder, and that command writes it there', + async () => { + const root = fs.realpathSync(tmpDir); + const cwd = path.join(root, 'project'); + const elsewhere = path.join(root, "someone's folder"); + fs.mkdirSync(cwd, {recursive: true}); + fs.mkdirSync(elsewhere, {recursive: true}); + // A home folder inside the temp folder turns scratch copies off, so a + // path outside the project is refused here as it is elsewhere. + const before = process.env.HOME; + process.env.HOME = path.join(root, 'home'); + try { + expect(tempFolders()).toEqual([]); + const given = path.join(elsewhere, 'pages', 'blank.tsx'); + const err = await templateApi('blank', {targetPath: given, cwd}).catch( + e => e, + ); + expect(err.code).toBe('ERR_PATH_TRAVERSAL'); + expect(err.suggestions.map(s => s.reason)).toEqual([ + 'write the page inside the project', + 'write the page where you named it, from its folder', + 'print the source and write nothing', + ]); + expect(err.suggestions[1].name).toBe( + `cd '${elsewhere.replace(/'/g, `'\\''`)}' && astryx template blank ./pages/blank.tsx`, + ); + expect(fs.readdirSync(elsewhere)).toEqual([]); + + // The named command, run from that folder, writes the path named. + const written = await templateApi('blank', { + targetPath: './pages/blank.tsx', + cwd: elsewhere, + }); + expect(written.data.fileName).toBe('blank.tsx'); + expect(fs.existsSync(given)).toBe(true); + } finally { + process.env.HOME = before; + } + }, + ); + + it('names no folder to run from when only the disk root exists', async () => { + const cwd = path.join(tmpDir, 'project'); + fs.mkdirSync(cwd, {recursive: true}); + const err = await templateApi('blank', { + targetPath: nowhere('deep', 'page.tsx'), + cwd, + }).catch(e => e); + expect(err.suggestions.some(s => s.name.startsWith('cd '))).toBe(false); + }); + it('keeps the flags as typed in the suggested commands', async () => { const cwd = path.join(tmpDir, 'project'); fs.mkdirSync(cwd, {recursive: true}); @@ -619,6 +671,34 @@ describe('template path text output', () => { 60_000, ); + it.skipIf(process.platform === 'win32')( + 'prints the run-from-its-folder command with the CLI invocation after the change of folder', + async () => { + const root = fs.realpathSync(tmpDir); + const cwd = fs.realpathSync(fs.mkdtempSync(path.join(root, 'cli-'))); + const elsewhere = path.join(root, 'elsewhere'); + fs.mkdirSync(elsewhere); + const before = process.env.HOME; + process.env.HOME = path.join(root, 'home'); + try { + const result = await runCli( + ['template', 'blank', path.join(elsewhere, 'dash.tsx')], + cwd, + ); + expect(result.status).toBe(1); + expect(result.stderr).toMatch( + new RegExp( + `cd ${elsewhere.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} && \\S.* template blank \\./dash\\.tsx\\s+\\(write the page where you named it, from its folder\\)`, + ), + ); + expect(result.stderr).not.toMatch(/&& astryx template/); + } finally { + process.env.HOME = before; + } + }, + 60_000, + ); + it('names the commands that work when the path is outside the project', async () => { const cwd = fs.realpathSync(fs.mkdtempSync(path.join(tmpDir, 'cli-'))); const scratch = nowhere('astryx_dash'); diff --git a/packages/cli/clients/cli/lib/cli-error.mjs b/packages/cli/clients/cli/lib/cli-error.mjs index ed3bb7c85bf24..10b3da3dd2976 100644 --- a/packages/cli/clients/cli/lib/cli-error.mjs +++ b/packages/cli/clients/cli/lib/cli-error.mjs @@ -134,10 +134,7 @@ export function cliError(message, options = {}) { if (suggestions?.length) { lines.push(''); for (const s of suggestions) { - // A suggested command stays bare in JSON and is prefixed here. - const name = /^astryx(\s|$)/.test(s.name) - ? formatCliCommand(s.name) - : s.name; + const name = shownCommand(s.name); const tag = s.reason ? ` ${name} (${s.reason})` : ` ${name}`; lines.push(tag); } @@ -327,3 +324,21 @@ export function themeGroupUnknownSubcommand(group, word, names, loaded) { ), }; } + +/** + * A suggested command as printed: it stays bare in JSON and the run that + * answers is prefixed here. A command run in another folder + * (commandInFolder) keeps its change of folder in front. + * @param {string} name + * @returns {string} + */ +function shownCommand(name) { + const inFolder = + /^(cd (?:-LiteralPath )?(?:'(?:[^']|'\\''|'')*'|\S+)(?: -ErrorAction Stop;| &&) )(.*)$/su.exec( + name, + ); + const [lead, command] = inFolder ? [inFolder[1], inFolder[2]] : ['', name]; + return /^astryx(\s|$)/.test(command) + ? `${lead}${formatCliCommand(command)}` + : name; +} diff --git a/packages/cli/clients/cli/lib/cli-error.test.mjs b/packages/cli/clients/cli/lib/cli-error.test.mjs index b4ee302a9dc58..41f24e1938317 100644 --- a/packages/cli/clients/cli/lib/cli-error.test.mjs +++ b/packages/cli/clients/cli/lib/cli-error.test.mjs @@ -18,6 +18,7 @@ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest'; import {cliError, assertOrExit, cliExit} from './cli-error.mjs'; import {setJsonMode, API_VERSION} from '../../../foundation/response/json.mjs'; +import {formatCliCommand} from '../../../foundation/env/package-manager.mjs'; describe('cliError — human mode', () => { let stderr; @@ -63,6 +64,28 @@ describe('cliError — human mode', () => { expect(stderr).toContain(' ButtonGroup (related)'); }); + it('keeps a change of folder in front of a suggested command it prefixes', () => { + expect(() => + cliError('Outside the project', { + suggestions: [ + { + name: "cd '/a b/it'\\''s' && astryx template blank ./x.tsx", + reason: 'here', + }, + { + name: 'cd -LiteralPath C:\\w -ErrorAction Stop; astryx template blank ./x.tsx', + }, + ], + }), + ).toThrow('__exit_1__'); + const shown = formatCliCommand('astryx template blank ./x.tsx'); + expect(shown).not.toBe('astryx template blank ./x.tsx'); + expect(stderr).toContain(` cd '/a b/it'\\''s' && ${shown} (here)`); + expect(stderr).toContain( + ` cd -LiteralPath C:\\w -ErrorAction Stop; ${shown}`, + ); + }); + it('omits "(reason)" when suggestion has no reason field', () => { expect(() => cliError('Unknown topic', {suggestions: [{name: 'color'}, {name: 'spacing'}]}), From a01d6fdaea7d8ac2bc7d725bff30431f61fbaacc Mon Sep 17 00:00:00 2001 From: Joey <17398284+josephfarina@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:31:52 -0800 Subject: [PATCH 2/4] fix(cli): the cd line covers .. paths, Core templates only, with that folder's CLI invocation; record DEC-20 [skip ci] --- .changeset/template-refusal-cd-hint.md | 2 +- docs/architecture/cli-surface.md | 23 +++++ packages/cli/api/template/_adapter.mjs | 32 +++++- packages/cli/api/template/copy/copy.mjs | 66 ++++++++----- .../template/template-integration.test.mjs | 41 ++++++++ packages/cli/api/template/template.mjs | 5 + .../commands/template.path-safety.test.mjs | 97 ++++++++++++++++++- .../clients/cli/lib/cli-error.folder.test.mjs | 64 ++++++++++++ packages/cli/clients/cli/lib/cli-error.mjs | 18 ++-- .../cli/clients/cli/lib/cli-error.test.mjs | 11 ++- .../cli/foundation/env/package-manager.mjs | 29 ++++++ .../foundation/env/package-manager.test.mjs | 26 +++++ 12 files changed, 373 insertions(+), 41 deletions(-) create mode 100644 packages/cli/clients/cli/lib/cli-error.folder.test.mjs diff --git a/.changeset/template-refusal-cd-hint.md b/.changeset/template-refusal-cd-hint.md index 9d6e27eb80560..5ee9d2566bdde 100644 --- a/.changeset/template-refusal-cd-hint.md +++ b/.changeset/template-refusal-cd-hint.md @@ -2,6 +2,6 @@ '@astryxdesign/cli': patch --- -[fix] When `astryx template ` refuses a path outside the project, it also names the command that writes that same path: a change to the nearest folder of it that exists, then the template command with the path from there. Printed, the CLI invocation follows the change of folder. +[feat] When `astryx template ` refuses the destination of a Core template that no integration replaces, outside the project (an absolute path, or one that leaves it through `..`), it also names the command that writes that same destination: a change to the nearest folder of it that exists, then the template command with the path from there, printed with the CLI invocation for that folder. A `..` path used to get the refusal with no command to run; it now gets the same commands as an absolute one. A `..` path that lands in the system temp folder is still not a scratch copy; the refusal names its absolute path, which takes one. @josephfarina diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.md index 6157c6c270e07..e59220d7659c2 100644 --- a/docs/architecture/cli-surface.md +++ b/docs/architecture/cli-surface.md @@ -1285,6 +1285,29 @@ Rejected: following the viewer for every page (a one-mode theme is unreadable in the other scheme), and running the theme module to read its modes (a render runs no theme code). +### DEC-20 — A refused template path names the same write from its folder + +**Decider:** `josephfarina`, `2026-11-18` + +When `astryx template ` refuses a destination outside the project +and outside the temp folder (named absolutely, from the home folder, or through +`..`), the refusal also names a command that writes that same destination: `cd` +into the nearest folder on the destination's path that exists, then run the +template command with the rest of the path, using the CLI command that folder +would use (`spec:AST-081` FR5). Run from that folder, the write stays inside +the folder the command runs from (INV10), so the caller gets the copy where +they named it without a second refusal. The command is named only for a Core +template that no integration replaces: outside the project the project's +integrations do not load, so an integration's template would not be found +there, and a replaced Core template would be the Core version instead of the +project's replacement. No command is named when no folder on the path exists +except the disk's root. A destination reached through `..` that lands in the +temp folder is not a scratch copy (DEC-15); the refusal names the same +destination as an absolute path, which DEC-15 accepts as a scratch copy. + +Rejected: writing the named destination from the current folder (it leaves the +folder a template write is confined to). + ## Verification | Invariant | Evidence | Failure signal | diff --git a/packages/cli/api/template/_adapter.mjs b/packages/cli/api/template/_adapter.mjs index dfc9a493c5e01..26c92802ec17a 100644 --- a/packages/cli/api/template/_adapter.mjs +++ b/packages/cli/api/template/_adapter.mjs @@ -4,12 +4,15 @@ * @file The `template` subject's adapter for icon mapping (AST-084 FR9), * which reads the project's icon sets through the `Project` seam, for the * project's component list, for the not-found hint that names another - * lookup command, and for the links and doc tokens in a template's - * description. + * lookup command, for the links and doc tokens in a template's + * description, and for the nearest folder a refused destination's command + * runs from. * * @position api/template — adapter read by the template dispatcher */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; import {Project} from '../../foundation/config/project.mjs'; import {linkOwnedTexts} from '../docs/_adapter.mjs'; import {NO_ICON_SETS} from '../../foundation/discovery/template-icons.mjs'; @@ -239,3 +242,28 @@ export async function withOtherCommandHint(name, suggestions, cwd, namesOf) { return suggestions; } } + +/** + * The nearest folder that exists at or above `dir`: where a command that + * writes a path below it runs from. The disk's root when no other folder on + * the path exists. + * @param {string} dir absolute + * @returns {string} + */ +export function nearestFolder(dir) { + let at = dir; + while (!isFolder(at) && path.dirname(at) !== at) at = path.dirname(at); + return at; +} + +/** + * @param {string} dir + * @returns {boolean} + */ +function isFolder(dir) { + try { + return fs.statSync(dir).isDirectory(); + } catch { + return false; + } +} diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs index 2e5ce019d084d..cd72a05668b6a 100644 --- a/packages/cli/api/template/copy/copy.mjs +++ b/packages/cli/api/template/copy/copy.mjs @@ -28,6 +28,8 @@ import { } from '../../../foundation/discovery/template-adapter.mjs'; import {analyzeTemplateNeeds} from '../../../foundation/discovery/template-needs.mjs'; import {templateDestination} from '../../../foundation/discovery/template-destination.mjs'; +import {CORE_PACKAGE_NAME} from '../../../foundation/identity/package-names.mjs'; +import {nearestFolder} from '../_adapter.mjs'; import { commandInFolder, quoteCommandArgument, @@ -41,12 +43,14 @@ import { * Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and * return the `template.copy` receipt. * @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} match - * @param {{targetPath: string, cwd: string, overwrite?: boolean, iconSets?: Parameters[1], components?: {ownersOf: (name: string) => readonly string[], qualified: boolean, documents?: (pkg: string, name: string) => boolean}, command?: string}} ctx + * @param {{targetPath: string, cwd: string, overwrite?: boolean, iconSets?: Parameters[1], components?: {ownersOf: (name: string) => readonly string[], qualified: boolean, documents?: (pkg: string, name: string) => boolean}, command?: string, replaced?: boolean}} ctx * `iconSets`: the project's icon sets; without them the icons are unchanged. * `components`: how `astryx component` reads the project's components * (loadComponentLookup); without it the receipt names no component. * `command`: the command that selects this template, without a path; the * refusal of a path outside the project suggests it + * `replaced`: whether an integration in the project replaces this + * template's id * @returns {import('../template.type.mjs').TemplateCopyResponse} */ export function templateCopy( @@ -58,6 +62,7 @@ export function templateCopy( iconSets = NO_ICON_SETS, components = {ownersOf: () => [], qualified: false}, command = `astryx template ${match.dirName} --type ${match.type}`, + replaced = false, }, ) { if (!fs.existsSync(match.filePath)) { @@ -97,11 +102,13 @@ export function templateCopy( }); } catch (err) { if (!(err instanceof PathSafetyError)) throw err; + // A path that leaves the project, absolute or through `..`; a link that + // carries it out is refused as before. const outsideProject = - path.isAbsolute(target) && - err.code === ERROR_CODES.ERR_PATH_TRAVERSAL && - !err.viaSymlink; - const temp = outsideProject ? tempFolderOf(target) : null; + err.code === ERROR_CODES.ERR_PATH_TRAVERSAL && !err.viaSymlink; + // Only a path named absolutely in the temp folder is a scratch copy. + const temp = + outsideProject && path.isAbsolute(target) ? tempFolderOf(target) : null; if (temp) { outputFilePath = inTempFolder(fileTarget, given, temp); scratch = true; @@ -111,17 +118,41 @@ export function templateCopy( // from its own folder, and the print that writes nothing. const folder = templateDestination(cwd, match.type, match.dirName); const [scratchFolder] = tempFolders(); - const there = fromNearestFolder(targetPath); + // A `..` path that lands in the temp folder: its absolute path takes + // the scratch copy it is not. + const absolute = path.isAbsolute(target) + ? null + : path.resolve(cwd, target) + (/[\\/]$/.test(target) ? path.sep : ''); + const scratchPath = absolute && tempFolderOf(absolute) ? absolute : null; + // The file the copy would write, so a folder named with a trailing + // separator is named by its file, not as a file of that name. Only a + // Core template no integration replaces: outside the project its + // integrations do not load, so an integration's template is not found + // there, and a replaced one would be the Core version. + const there = + scratchPath || replaced || pkgOf(match) !== CORE_PACKAGE_NAME + ? null + : fromNearestFolder(path.resolve(cwd, fileTarget)); throw new AstryxError( `Invalid template target path "${given}": it is outside the project root (${path.resolve(cwd)}). ` + - (scratchFolder - ? `The template is written only inside the project, or as a scratch copy in the system temp folder (${scratchFolder}). Give a path inside one, or print the source.` - : 'The template is written only inside the project. Give a path inside it, or print the source.'), + (scratchPath + ? `A scratch copy in the system temp folder takes its absolute path, ${scratchPath}.` + : scratchFolder + ? `The template is written only inside the project, or as a scratch copy in the system temp folder (${scratchFolder}). Give a path inside one, or print the source.` + : 'The template is written only inside the project. Give a path inside it, or print the source.'), [ { name: `${command} ${quoteCommandArgument(folder)}`, reason: `write the ${match.type} inside the project`, }, + ...(scratchPath + ? [ + { + name: `${command} ${quoteCommandArgument(scratchPath)}`, + reason: 'take a scratch copy in the system temp folder', + }, + ] + : []), ...(there ? [ { @@ -248,25 +279,12 @@ function inTempFolder(file, given, temp) { * of it that exists, and the path from there. From that folder the path is * inside the current folder, so the copy writes it there. Null when only the * disk's root exists, which is no place to run a project command from. - * @param {string} target the destination as named, absolute + * @param {string} target the file the copy would write, absolute * @returns {{dir: string, path: string} | null} */ function fromNearestFolder(target) { - let dir = path.dirname(target); - while (!isFolder(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir); + const dir = nearestFolder(path.dirname(target)); if (path.dirname(dir) === dir) return null; const rel = path.relative(dir, target).split(path.sep).join('/'); return {dir, path: `./${rel}`}; } - -/** - * @param {string} dir - * @returns {boolean} - */ -function isFolder(dir) { - try { - return fs.statSync(dir).isDirectory(); - } catch { - return false; - } -} diff --git a/packages/cli/api/template/template-integration.test.mjs b/packages/cli/api/template/template-integration.test.mjs index c666fc746d9cf..8723ae04bff8f 100644 --- a/packages/cli/api/template/template-integration.test.mjs +++ b/packages/cli/api/template/template-integration.test.mjs @@ -300,6 +300,47 @@ describe('integration template discovery', () => { expect(result.data.type).toBe('page'); }); + it('names no run-from-its-folder command for an integration template, which a folder outside the project cannot find', async () => { + const pkgDir = installWidgets(tmpDir); + writeTemplate(pkgDir, 'pricing', {kind: 'page'}); + const outside = path.join( + path.dirname(tmpDir), + `astryx-no-such-folder-${path.basename(tmpDir)}`, + 'pricing.tsx', + ); + + const err = await template('pricing', { + type: 'page', + targetPath: outside, + cwd: tmpDir, + }).catch(e => e); + expect(err.code).toBe('ERR_PATH_TRAVERSAL'); + expect(err.suggestions.length).toBeGreaterThan(0); + expect(err.suggestions.some(s => s.name.startsWith('cd '))).toBe(false); + expect(fs.existsSync(path.dirname(outside))).toBe(false); + }); + + it('names no run-from-its-folder command for a Core template an integration replaces, even asked for by package', async () => { + const pkgDir = installWidgets(tmpDir); + writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'}); + declareReplaces(pkgDir, {'acme-app-shell': 'shell-side-nav'}); + const outside = path.join( + path.dirname(tmpDir), + `astryx-no-such-folder-${path.basename(tmpDir)}`, + 'shell.tsx', + ); + for (const options of [{}, {package: '@astryxdesign/core'}]) { + const err = await template('shell-side-nav', { + type: 'page', + ...options, + targetPath: outside, + cwd: tmpDir, + }).catch(e => e); + expect(err.code, JSON.stringify(options)).toBe('ERR_PATH_TRAVERSAL'); + expect(err.suggestions.some(s => s.name.startsWith('cd '))).toBe(false); + } + }); + it('copies a page template into a directory as page.tsx', async () => { const pkgDir = installWidgets(tmpDir); writeTemplate(pkgDir, 'pricing', {kind: 'page'}); diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs index c5bd126536639..6933d2da99859 100644 --- a/packages/cli/api/template/template.mjs +++ b/packages/cli/api/template/template.mjs @@ -317,5 +317,10 @@ async function templateRead(name, options = {}) { iconSets, components, command, + // An integration that replaces this id, even when the Core original is + // asked for by package. + replaced: templates.some( + t => t.replaces === match.dirName && !t.replacementRejected, + ), }); } diff --git a/packages/cli/clients/cli/commands/template.path-safety.test.mjs b/packages/cli/clients/cli/commands/template.path-safety.test.mjs index e22cb9cf0cb88..182483cec8cbe 100644 --- a/packages/cli/clients/cli/commands/template.path-safety.test.mjs +++ b/packages/cli/clients/cli/commands/template.path-safety.test.mjs @@ -148,8 +148,8 @@ describe('template path safety', () => { const before = process.env.HOME; process.env.HOME = path.join(root, 'home'); try { - expect(tempFolders()).toEqual([]); const given = path.join(elsewhere, 'pages', 'blank.tsx'); + expect(tempFolderOf(given)).toBeNull(); const err = await templateApi('blank', {targetPath: given, cwd}).catch( e => e, ); @@ -177,6 +177,101 @@ describe('template path safety', () => { }, ); + it.skipIf(process.platform === 'win32')( + 'names a folder given with a trailing separator by the file the copy writes in it', + async () => { + const root = fs.realpathSync(tmpDir); + const cwd = path.join(root, 'project'); + const elsewhere = path.join(root, 'out'); + fs.mkdirSync(cwd, {recursive: true}); + fs.mkdirSync(elsewhere); + const before = process.env.HOME; + process.env.HOME = path.join(root, 'home'); + try { + const given = `${path.join(elsewhere, 'foo.tsx')}${path.sep}`; + expect(tempFolderOf(given)).toBeNull(); + const err = await templateApi('blank', {targetPath: given, cwd}).catch( + e => e, + ); + expect(err.suggestions[1].name).toBe( + `cd ${elsewhere} && astryx template blank ./foo.tsx/page.tsx`, + ); + } finally { + process.env.HOME = before; + } + }, + ); + + it.skipIf(process.platform === 'win32')( + 'refuses a `..` path out of the project with the same commands as an absolute one', + async () => { + const root = fs.realpathSync(tmpDir); + const cwd = path.join(root, 'project'); + fs.mkdirSync(cwd, {recursive: true}); + fs.mkdirSync(path.join(root, 'outside')); + const before = process.env.HOME; + process.env.HOME = path.join(root, 'home'); + try { + expect(tempFolderOf(path.join(root, 'outside'))).toBeNull(); + const err = await templateApi('blank', { + targetPath: '../outside/app', + cwd, + }).catch(e => e); + expect(err.code).toBe('ERR_PATH_TRAVERSAL'); + expect(err.message).toContain( + 'Invalid template target path "../outside/app": it is outside the project root', + ); + expect(err.suggestions).toEqual([ + { + name: 'astryx template blank src/pages/blank.tsx', + reason: 'write the page inside the project', + }, + { + name: `cd ${path.join(root, 'outside')} && astryx template blank ./app/page.tsx`, + reason: 'write the page where you named it, from its folder', + }, + { + name: 'astryx template blank', + reason: 'print the source and write nothing', + }, + ]); + expect(fs.readdirSync(path.join(root, 'outside'))).toEqual([]); + } finally { + process.env.HOME = before; + } + }, + ); + + it.skipIf(!tmpTakesScratch)( + 'never takes a `..` path into the temp folder as a scratch copy, and names its absolute path, which does', + async () => { + const root = fs.realpathSync(tmpDir); + const cwd = path.join(root, 'project'); + fs.mkdirSync(cwd, {recursive: true}); + const err = await templateApi('blank', { + targetPath: '../scratch', + cwd, + }).catch(e => e); + expect(err.code).toBe('ERR_PATH_TRAVERSAL'); + expect(err.message).toContain( + `A scratch copy in the system temp folder takes its absolute path, ${path.join(root, 'scratch')}.`, + ); + expect(err.suggestions.map(s => s.name)).toEqual([ + 'astryx template blank src/pages/blank.tsx', + `astryx template blank ${path.join(root, 'scratch')}`, + 'astryx template blank', + ]); + expect(fs.existsSync(path.join(root, 'scratch'))).toBe(false); + + // The named absolute path takes the scratch copy. + const written = await templateApi('blank', { + targetPath: path.join(root, 'scratch'), + cwd, + }); + expect(written.data.outputDir).toBe(path.join(root, 'scratch')); + }, + ); + it('names no folder to run from when only the disk root exists', async () => { const cwd = path.join(tmpDir, 'project'); fs.mkdirSync(cwd, {recursive: true}); diff --git a/packages/cli/clients/cli/lib/cli-error.folder.test.mjs b/packages/cli/clients/cli/lib/cli-error.folder.test.mjs new file mode 100644 index 0000000000000..c2acd76f59921 --- /dev/null +++ b/packages/cli/clients/cli/lib/cli-error.folder.test.mjs @@ -0,0 +1,64 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file A suggested command run in another folder is printed with the CLI + * invocation chosen for that folder, not for the current one. + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {setJsonMode} from '../../../foundation/response/json.mjs'; + +vi.mock('../../../foundation/env/package-manager.mjs', async importOriginal => { + const actual = /** @type {any} */ (await importOriginal()); + return { + ...actual, + formatCliCommand: ( + /** @type {string} */ command, + /** @type {string} */ dir, + ) => `RUN<${dir ?? 'here'}> ${command.replace(/^astryx\s*/, '')}`, + }; +}); + +const {cliError} = await import('./cli-error.mjs'); + +describe('cliError — a suggestion that changes folder', () => { + /** @type {string[]} */ + let stderr; + beforeEach(() => { + setJsonMode(false); + stderr = []; + vi.spyOn(console, 'error').mockImplementation((...a) => + stderr.push(a.join(' ')), + ); + vi.spyOn(process, 'exit').mockImplementation(() => { + throw new Error('__exit__'); + }); + }); + afterEach(() => vi.restoreAllMocks()); + + it('chooses the invocation for the folder after the change of folder', () => { + expect(() => + cliError('Outside the project', { + suggestions: [ + {name: 'astryx template blank src/pages/blank.tsx', reason: 'inside'}, + { + name: "cd '/a b/it'\\''s' && astryx template blank ./x.tsx", + reason: 'there', + }, + { + name: 'cd -LiteralPath C:\\w -ErrorAction Stop; astryx template blank ./x.tsx', + }, + ], + }), + ).toThrow('__exit__'); + expect(stderr).toContain( + ' RUN template blank src/pages/blank.tsx (inside)', + ); + expect(stderr).toContain( + " cd '/a b/it'\\''s' && RUN template blank ./x.tsx (there)", + ); + expect(stderr).toContain( + ' cd -LiteralPath C:\\w -ErrorAction Stop; RUN template blank ./x.tsx', + ); + }); +}); diff --git a/packages/cli/clients/cli/lib/cli-error.mjs b/packages/cli/clients/cli/lib/cli-error.mjs index 10b3da3dd2976..588a2caf5eae6 100644 --- a/packages/cli/clients/cli/lib/cli-error.mjs +++ b/packages/cli/clients/cli/lib/cli-error.mjs @@ -60,6 +60,7 @@ import {setOutcome} from '../../../foundation/debug/index.mjs'; import { formatCliCommand, getCliInvocation, + splitCommandInFolder, } from '../../../foundation/env/package-manager.mjs'; import {levenshteinDistance} from '../../../foundation/text/levenshtein.mjs'; import {doc as experimentalEditorDoc} from '../commands/experimental-theme-editor.doc.mjs'; @@ -328,17 +329,16 @@ export function themeGroupUnknownSubcommand(group, word, names, loaded) { /** * A suggested command as printed: it stays bare in JSON and the run that * answers is prefixed here. A command run in another folder - * (commandInFolder) keeps its change of folder in front. + * (commandInFolder) keeps its change of folder in front, and its invocation + * is chosen for that folder (`spec:AST-081` FR5). * @param {string} name * @returns {string} */ function shownCommand(name) { - const inFolder = - /^(cd (?:-LiteralPath )?(?:'(?:[^']|'\\''|'')*'|\S+)(?: -ErrorAction Stop;| &&) )(.*)$/su.exec( - name, - ); - const [lead, command] = inFolder ? [inFolder[1], inFolder[2]] : ['', name]; - return /^astryx(\s|$)/.test(command) - ? `${lead}${formatCliCommand(command)}` - : name; + const inFolder = splitCommandInFolder(name); + if (inFolder && /^astryx(\s|$)/.test(inFolder.command)) { + const lead = name.slice(0, name.length - inFolder.command.length); + return `${lead}${formatCliCommand(inFolder.command, inFolder.dir)}`; + } + return /^astryx(\s|$)/.test(name) ? formatCliCommand(name) : name; } diff --git a/packages/cli/clients/cli/lib/cli-error.test.mjs b/packages/cli/clients/cli/lib/cli-error.test.mjs index 41f24e1938317..870bd01cbf419 100644 --- a/packages/cli/clients/cli/lib/cli-error.test.mjs +++ b/packages/cli/clients/cli/lib/cli-error.test.mjs @@ -78,11 +78,14 @@ describe('cliError — human mode', () => { ], }), ).toThrow('__exit_1__'); - const shown = formatCliCommand('astryx template blank ./x.tsx'); - expect(shown).not.toBe('astryx template blank ./x.tsx'); - expect(stderr).toContain(` cd '/a b/it'\\''s' && ${shown} (here)`); + const shown = (/** @type {string} */ dir) => + formatCliCommand('astryx template blank ./x.tsx', dir); + expect(shown("/a b/it's")).not.toBe('astryx template blank ./x.tsx'); expect(stderr).toContain( - ` cd -LiteralPath C:\\w -ErrorAction Stop; ${shown}`, + ` cd '/a b/it'\\''s' && ${shown("/a b/it's")} (here)`, + ); + expect(stderr).toContain( + ` cd -LiteralPath C:\\w -ErrorAction Stop; ${shown('C:\\w')}`, ); }); diff --git a/packages/cli/foundation/env/package-manager.mjs b/packages/cli/foundation/env/package-manager.mjs index 277a092075b95..66cb27f1e6d06 100644 --- a/packages/cli/foundation/env/package-manager.mjs +++ b/packages/cli/foundation/env/package-manager.mjs @@ -774,3 +774,32 @@ export function commandInFolder(dir, command, platform = process.platform) { ? `cd -LiteralPath ${folder} -ErrorAction Stop; ${command}` : `cd ${folder} && ${command}`; } + +/** + * The folder and the command of a line {@link commandInFolder} printed, in + * either form; null for any other line. A printer reads it to choose the CLI + * invocation for the folder the command runs in, not the current one. + * + * @param {string} line + * @returns {{dir: string, command: string} | null} + */ +export function splitCommandInFolder(line) { + const posix = /^cd ('(?:[^']|'\\'')*'|[^\s']+) && (.*)$/su.exec(line); + if (posix) { + const [, folder, command] = posix; + const dir = folder.startsWith("'") + ? folder.slice(1, -1).replace(/'\\''/gu, "'") + : folder; + return {dir, command}; + } + const powershell = + /^cd -LiteralPath ('(?:[^']|'')*'|\S+) -ErrorAction Stop; (.*)$/su.exec(line); + if (powershell) { + const [, folder, command] = powershell; + const dir = folder.startsWith("'") + ? folder.slice(1, -1).replace(/(['\u2018\u2019\u201A\u201B])\1/gu, '$1') + : folder; + return {dir, command}; + } + return null; +} diff --git a/packages/cli/foundation/env/package-manager.test.mjs b/packages/cli/foundation/env/package-manager.test.mjs index 8f1cce7981ced..c2627e934777e 100644 --- a/packages/cli/foundation/env/package-manager.test.mjs +++ b/packages/cli/foundation/env/package-manager.test.mjs @@ -17,6 +17,7 @@ import { prefixCliCommands, quoteCommandArgument, commandInFolder, + splitCommandInFolder, } from './package-manager.mjs'; import {recordDeclaredSettings, runWithCliDoor} from './cli-command.mjs'; import {CLI_VERSION} from '../../test-utils/release-fixtures.mjs'; @@ -814,6 +815,31 @@ describe('quoteCommandArgument', () => { }); }); +describe('splitCommandInFolder', () => { + it('reads back the folder and the command of every line commandInFolder prints', () => { + for (const [dir, platform] of [ + ['/srv/app', 'linux'], + ["/tmp/it's here", 'linux'], + ['/a b/c && d', 'darwin'], + ['C:\\a[1] b', 'win32'], + ["C:\\it's", 'win32'], + ['C:\\Macy\u2019s', 'win32'], + ]) { + const line = commandInFolder(dir, 'astryx template blank ./x.tsx', platform); + expect(splitCommandInFolder(line), line).toEqual({ + dir, + command: 'astryx template blank ./x.tsx', + }); + } + }); + + it('reads no folder from any other line', () => { + for (const line of ['astryx docs', 'cd', 'cd /x', 'cd /x; astryx docs']) { + expect(splitCommandInFolder(line), line).toBeNull(); + } + }); +}); + describe('commandInFolder', () => { it('enters the folder, then runs the command only if that worked, in a POSIX shell', () => { expect(commandInFolder('/tmp/my app', 'npx x', 'linux')).toBe( From 02df385d0779cceb43458fce132f9d5fb50ef6e2 Mon Sep 17 00:00:00 2001 From: Joey Farina Date: Thu, 19 Nov 2026 11:40:51 -0800 Subject: [PATCH 3/4] fix(cli): doctor outside a project names the issues of an integration installed for the computer Outside a project, component, template, search, discover and theme print one line when an integration installed for the computer has issues in its contributions, and send the reader to doctor. Doctor's computer-integrations check passed and named nothing, so the pointer led nowhere. It now warns and names each issue. Its fix says that a newer release of the package must fix it, with the command that updates a third-party package beside a CLI installed for the computer, or that a tool's package set updates it. Doctor reads no Core outside a project, so it leaves out the issues that compare components with Core components. [skip ci] --- .../doctor-computer-integration-issues.md | 7 ++ docs/specs/AST-081-global-mode/spec.md | 9 +- packages/cli/api/doctor/_adapter.mjs | 88 +++++++++++++----- packages/cli/api/doctor/doctor.doc.mjs | 2 +- packages/cli/api/doctor/doctor.mjs | 45 ++++++++- packages/cli/api/doctor/doctor.test.mjs | 72 +++++++++++++++ .../docs/tree/computer-integrations.doc.mjs | 2 +- .../cli/clients/cli/commands/doctor.doc.mjs | 2 +- .../discovery/component-replacement.mjs | 13 +++ .../integrations/integration-warnings.mjs | 15 ++- packages/cli/foundation/release/notices.mjs | 66 ++++++++++++-- .../cli/foundation/release/notices.test.mjs | 40 ++++++++ .../cli/test/global-local.rows-16-39.test.mjs | 91 +++++++++++++++++++ 13 files changed, 406 insertions(+), 46 deletions(-) create mode 100644 .changeset/doctor-computer-integration-issues.md diff --git a/.changeset/doctor-computer-integration-issues.md b/.changeset/doctor-computer-integration-issues.md new file mode 100644 index 0000000000000..018fea0e95573 --- /dev/null +++ b/.changeset/doctor-computer-integration-issues.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[fix] Outside a project, `astryx doctor` now warns about an integration installed for the computer that has issues in its own files, and names them. Before, commands such as `astryx search` and `astryx discover` warned about the integration and said to run `astryx doctor`, but `doctor` passed and named no issue. Issues that need a comparison with Core components are still not named there, because `doctor` reads no Core outside a project. + +@josephfarina diff --git a/docs/specs/AST-081-global-mode/spec.md b/docs/specs/AST-081-global-mode/spec.md index 3ebd3ca296129..d8bbd6968448e 100644 --- a/docs/specs/AST-081-global-mode/spec.md +++ b/docs/specs/AST-081-global-mode/spec.md @@ -780,8 +780,11 @@ works on is `spec:AST-040` FR9's. copy. - `doctor` outside a project lists each computer-level integration it uses and each the folder loads its own copy of, and warns about each it skips or - cannot load, naming why; inside a project, it lists the ones `discover` - lists as available, with the same install command or guidance. + cannot load, naming why. It also warns about each issue in the + contributions of one it uses that the everyday commands point to `doctor` + for, except issues that need a comparison with Core components: it reads no + Core there (FR3). Inside a project, it lists the ones `discover` lists as + available, with the same install command or guidance. - **FR13 — The repository may ship one plugin skill, shared by the Claude Code and Codex plugins.** The repository MAY ship one plugin skill, shared @@ -979,7 +982,7 @@ needs no Changeset. | FR9 | Hand-off probes: every command example run through each copy in each folder kind, compared with the release FR2 names run directly in that folder | the CLI package installed for the computer on an older and on a newer release than the project's CLI, run directly and run by a package runner in place of a fetch; a package runner's copy, unversioned and with a version requested inside a project, for a read and for `upgrade`; a project with Core but no CLI, through a package runner that fetches the newest release; a package with no Astryx inside a project, which the package runner takes for the project; a project CLI that predates the hand-off and one that hands off itself; a declined project CLI; a project CLI that cannot start; a non-zero exit; piped standard input; outside a project; text and JSON | A release other than the one FR2 names answers in a project, outside the declined case; a project CLI that differs from its Core answers; a requested version answers inside a project; a run is handed off twice or returns to a copy it left; arguments, folder, streams, or exit status differ from a direct run of the project's CLI; outside a project, a release answers that FR3 and FR6 do not name; or the line is missing, prints twice, prints in JSON mode, or prints for a run the project's own CLI answers directly | | FR10 | Notice tests | the global copy behind, for npm, pnpm, Yarn, Bun, and Volta installs; a newest release that needs a newer Node; a project behind, with and without its own CLI, and with a theme Astryx releases with Core; an old `astryx` first on the search path; two runs in one day and a run the next day; a failed command; JSON mode; `CI`; `NO_UPDATE_NOTIFIER`; standard error not a terminal; a prerelease | A notice prints in JSON mode, after a failure, twice in a day, with `CI` or `NO_UPDATE_NOTIFIER` set, or before the command's output; it names another package manager's command; or `doctor` omits it | | FR11 | One test per row of the global and project table, with packed CLI copies in each install layout | every row of the table | A row's answer, line, or test differs from the table, or a row has no test | -| FR12 | Computer-level integration tests and table rows G35–G43 | npm and pnpm global folders; a door's package set; a runner's temporary install; the release cache; outside a project; inside one with and without the same integration; an incompatible peer range; a manifest that fails | A computer-level integration contributes inside a project, is missing outside one, loads beside the project's copy, loads with an excluded peer range, or `discover` and `doctor` omit it | +| FR12 | Computer-level integration tests and table rows G35–G43 | npm and pnpm global folders; a door's package set; a runner's temporary install; the release cache; outside a project; inside one with and without the same integration; an incompatible peer range; a manifest that fails; a used integration whose contributions have issues | A computer-level integration contributes inside a project, is missing outside one, loads beside the project's copy, loads with an excluded peer range, `discover` and `doctor` omit it, or `doctor` passes while the everyday commands point at it for an issue that needs no Core | | FR13 | Plugin-skill drift check (`--check`) and `scripts/generate-agent-plugin-skill.test.mjs` | the committed plugin skill matches its rendering; a different rendering; a missing file | The committed file differs from the rendering and the check passes, or the skill is edited by hand | ## Decision log diff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjs index 21014128d9cd7..fcc516287a89c 100644 --- a/packages/cli/api/doctor/_adapter.mjs +++ b/packages/cli/api/doctor/_adapter.mjs @@ -17,6 +17,7 @@ import { listedPackageInstall, projectAddCommand, globalBehind, + globalUpdateBesideCli, globalUpgradeCommand, lastNoticeSkip, projectLag, @@ -113,6 +114,9 @@ import { } from '../../foundation/discovery/module-exports.mjs'; import {cssImports} from '../../foundation/render/embedded-imports.mjs'; import {postcss} from '../../foundation/runtime/lazy-dependencies.mjs'; +import {hostedRun} from '../../foundation/runtime/package-root.mjs'; +import {pointsToDoctor} from '../../foundation/integrations/integration-warnings.mjs'; +import {CORE_COMPARISON_CODES} from '../../foundation/discovery/component-replacement.mjs'; import {isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs'; import * as path from 'node:path'; import { @@ -1440,38 +1444,74 @@ export function readPackageJson(file) { /** * The integrations installed for the computer, and, outside a project, which - * of them the folder loads (spec AST-081 FR12): those it uses, and the names - * of the integrations the folder loads itself, whose copies win. + * of them the folder loads (spec AST-081 FR12): those it uses, the issues in + * their contributions, and the names of the integrations the folder loads + * itself, whose copies win. Also how such a package is updated: the command + * beside a CLI installed for the computer, or by the tool whose package set + * runs this CLI. * @param {string} cwd - * @returns {Promise<{computerIntegrations: import('../../foundation/integrations/computer-integrations.mjs').ComputerIntegrationCandidate[], loadedComputerIntegrations: string[], folderIntegrations: string[]}>} + * @returns {Promise<{computerIntegrations: import('../../foundation/integrations/computer-integrations.mjs').ComputerIntegrationCandidate[], loadedComputerIntegrations: string[], computerIntegrationIssues: Array<{package: string, severity: string, message: string}>, folderIntegrations: string[], integrationUpdate: ((name: string) => string | null) | null, integrationsUpdateWithTool: boolean}>} */ export async function computerIntegrationsOutside(cwd) { const computerIntegrations = computerIntegrationCandidates(cwd); - if (computerIntegrations.length === 0) { - return { - computerIntegrations, - loadedComputerIntegrations: [], - folderIntegrations: [], - }; + const globalCopy = isGlobalCopy(CLI_ROOT); + const update = { + integrationUpdate: globalCopy + ? (/** @type {string} */ name) => globalUpdateBesideCli(CLI_ROOT, name) + : null, + integrationsUpdateWithTool: hostedRun() != null, + }; + const none = { + computerIntegrations, + loadedComputerIntegrations: [], + computerIntegrationIssues: [], + folderIntegrations: [], + ...update, + }; + if (computerIntegrations.length === 0) return none; + /** @type {import('../../foundation/config/project.mjs').Project} */ + let project; + try { + project = await Project.load(cwd, {core: 'project'}); + } catch { + return none; } + /** @type {Array<{name: string, __computer?: boolean, __loadError?: string}>} */ + const loaded = project.loadedIntegrations; + const used = loaded + .filter(i => i.__computer && !i.__loadError) + .map(i => i.name); + // The everyday commands count these issues when they point at doctor, so + // doctor names them. Doctor reads no Core outside a project, so it leaves + // out the comparisons with Core components; the everyday commands judge + // those against the Core they carry. Core's templates come with the CLI. + const names = new Set(used); + const noCore = project.coreDir() == null; + /** @type {Array<{package: string, severity: string, message: string}>} */ + let issues = []; try { - const project = await Project.load(cwd, {core: 'project'}); - /** @type {Array<{name: string, __computer?: boolean, __loadError?: string}>} */ - const loaded = project.loadedIntegrations; - return { - computerIntegrations, - loadedComputerIntegrations: loaded - .filter(i => i.__computer && !i.__loadError) - .map(i => i.name), - folderIntegrations: loaded.filter(i => !i.__computer).map(i => i.name), - }; + issues = (await project.issues()) + .filter( + issue => + names.has(issue.package) && + pointsToDoctor(issue) && + !(noCore && CORE_COMPARISON_CODES.has(issue.code)), + ) + .map(issue => ({ + package: issue.package, + severity: issue.severity, + message: issue.message, + })); } catch { - return { - computerIntegrations, - loadedComputerIntegrations: [], - folderIntegrations: [], - }; + // The integrations loaded; only their issues could not be read. } + return { + computerIntegrations, + loadedComputerIntegrations: used, + computerIntegrationIssues: issues, + folderIntegrations: loaded.filter(i => !i.__computer).map(i => i.name), + ...update, + }; } /** diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjs index 5aa7158dcd75c..759dc9ba7664f 100644 --- a/packages/cli/api/doctor/doctor.doc.mjs +++ b/packages/cli/api/doctor/doctor.doc.mjs @@ -24,7 +24,7 @@ export const doc = { 'integration provider identity and contribution issues, agent docs, the ' + 'detected package manager, and the health of the docs the CLI reads (authoring ' + 'and CLI docs, the docs tree, doc size), and returns a structured ' + - 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add, and the `themes` check counts a theme as wired when package.json `astryx.theme` names one or when the source of the app (JavaScript, TypeScript and CSS files, outside dependencies and build output; type-only imports do not count) imports the built module or stylesheet of a discovered theme, the same imports theme add writes, or passes one to Theme (followed through module-scope variables, defineTheme extends, re-exports and installed packages; only a theme whose package is installed, or a local theme, counts), naming the file; a theme passed to Theme that cannot be traced, such as a prop or a variable declared inside a component, is reported as unconfirmed (info), not as missing. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust. Outside a project it checks the computer instead: the Node version (`node-version`), the release that answered (`answering-release`), the newest release the computer knows of (`newest-release`), the astryx commands on the search path (`cli-on-path`), the integrations installed for the computer (`computer-integrations`: each one used outside a project, and a warning for one skipped because its peer range excludes the answering release or that fails to load), and the computer-level agent text (`computer-agent-text`): present and matching this release, present but different, edited, absent, or turned off, and where it is linked, with `{@command init --user}` as the fix for the stale and absent cases, and each folder outside a project that `{@command init} --to` saved. The agent-text check is always info. In a project that saves a skill place in astryx.config `skills.to`, or holds a project skill, the `skill-places` check passes when each saved skill file matches this release and warns when one is missing or stale, when the copies of one place differ (one edited or not written by Astryx, the other written by Astryx or missing), when the block and a project skill copy are both there without both being saved (both saved passes, with a note), when a project skill is named `astryx`, the name of the computer-level skill, when a saved place is linked out of the project (not checked), or when the project skill cannot be rendered; an edited skill file is kept and named. It also reports integration skills (`spec:AST-046` FR15): a missing, stale or kept copy, a leftover copy Astryx wrote for a skill that is no longer kept, and a skill an integration declares that is left out, the last also in a project that keeps only the AGENTS.md block. A project that saves no `agents-md` place gets its verdict from this check: `agent-docs` names its skill files and points here. The newest-release check also runs inside a project: it names a newer release when the computer knows of one; inside a project whose release is older it names the install and upgrade commands; outside one, when the CLI installed for the computer is older, it names the command of the package manager that installed it, after the Node the newest release needs when the computer runs an older one. With no update check recorded, it says the newest release is not known, that only a copy installed for the computer checks (once a day), that a project changes its own copy only when it upgrades it, and that a tool that runs its own copy chooses its release. It is always info and installs nothing. The `cli-on-path` check also runs inside a project: it lists every astryx command on the search path in order, passes when the first is a release that hands each project run to the release of that project, and warns when the first is another program or a release that predates the hand-off, naming `{@pm install @astryxdesign/cli@latest --global}`. Inside a project, `computer-integrations` lists, as info, the integrations installed for the computer that the project does not install, with its install command; they are not used there. It never fails a check because the folder has no project, and installs nothing.' + + 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add, and the `themes` check counts a theme as wired when package.json `astryx.theme` names one or when the source of the app (JavaScript, TypeScript and CSS files, outside dependencies and build output; type-only imports do not count) imports the built module or stylesheet of a discovered theme, the same imports theme add writes, or passes one to Theme (followed through module-scope variables, defineTheme extends, re-exports and installed packages; only a theme whose package is installed, or a local theme, counts), naming the file; a theme passed to Theme that cannot be traced, such as a prop or a variable declared inside a component, is reported as unconfirmed (info), not as missing. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust. Outside a project it checks the computer instead: the Node version (`node-version`), the release that answered (`answering-release`), the newest release the computer knows of (`newest-release`), the astryx commands on the search path (`cli-on-path`), the integrations installed for the computer (`computer-integrations`: each one used outside a project, and a warning for one skipped because its peer range excludes the answering release, that fails to load, or whose contributions have issues, which it names. Outside a project it reads no Core, so it does not compare the components of a package with Core components), and the computer-level agent text (`computer-agent-text`): present and matching this release, present but different, edited, absent, or turned off, and where it is linked, with `{@command init --user}` as the fix for the stale and absent cases, and each folder outside a project that `{@command init} --to` saved. The agent-text check is always info. In a project that saves a skill place in astryx.config `skills.to`, or holds a project skill, the `skill-places` check passes when each saved skill file matches this release and warns when one is missing or stale, when the copies of one place differ (one edited or not written by Astryx, the other written by Astryx or missing), when the block and a project skill copy are both there without both being saved (both saved passes, with a note), when a project skill is named `astryx`, the name of the computer-level skill, when a saved place is linked out of the project (not checked), or when the project skill cannot be rendered; an edited skill file is kept and named. It also reports integration skills (`spec:AST-046` FR15): a missing, stale or kept copy, a leftover copy Astryx wrote for a skill that is no longer kept, and a skill an integration declares that is left out, the last also in a project that keeps only the AGENTS.md block. A project that saves no `agents-md` place gets its verdict from this check: `agent-docs` names its skill files and points here. The newest-release check also runs inside a project: it names a newer release when the computer knows of one; inside a project whose release is older it names the install and upgrade commands; outside one, when the CLI installed for the computer is older, it names the command of the package manager that installed it, after the Node the newest release needs when the computer runs an older one. With no update check recorded, it says the newest release is not known, that only a copy installed for the computer checks (once a day), that a project changes its own copy only when it upgrades it, and that a tool that runs its own copy chooses its release. It is always info and installs nothing. The `cli-on-path` check also runs inside a project: it lists every astryx command on the search path in order, passes when the first is a release that hands each project run to the release of that project, and warns when the first is another program or a release that predates the hand-off, naming `{@pm install @astryxdesign/cli@latest --global}`. Inside a project, `computer-integrations` lists, as info, the integrations installed for the computer that the project does not install, with its install command; they are not used there. It never fails a check because the folder has no project, and installs nothing.' + ' In global mode: with `cwd` outside a project, it checks the computer instead (the Node version, the version that answered, the newest version it knows of, the astryx commands on the search path, the integrations installed globally, and the agent guide for the computer) and never fails a check because the folder has no project. See {@link namespace:global} and {@link generic:who-answers}.', importPath: '@astryxdesign/cli/api', signature: 'doctor(options?: DoctorOptions): Promise', diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs index 5a30346285603..5d15765b15610 100644 --- a/packages/cli/api/doctor/doctor.mjs +++ b/packages/cli/api/doctor/doctor.mjs @@ -2704,6 +2704,13 @@ export function checkInstallGuidance(ctx) { * the integrations installed beside the running CLI * @property {string[]} [loadedComputerIntegrations] the names of those that * loaded outside a project + * @property {Array<{package: string, severity: string, message: string}>} [computerIntegrationIssues] + * the issues in the contributions of those that loaded + * @property {((name: string) => string | null) | null} [integrationUpdate] + * the command that updates one of them, beside a CLI installed for the + * computer + * @property {boolean} [integrationsUpdateWithTool] they sit in a tool's + * package set, which updates them * @property {string[]} [folderIntegrations] the names of the integrations the * folder loads itself, whose copies win over the computer's */ @@ -3034,7 +3041,9 @@ export function checkComputerAgentText(ctx) { /** * The integrations installed for the computer (spec AST-081 FR12). Outside a * project: each one that loads, and a warning for each that is skipped - * because its peer ranges exclude the answering release, or fails to load. + * because its peer ranges exclude the answering release, fails to load, or + * has issues in its contributions. The everyday commands print one line for + * such issues that points here. * @param {ComputerContext} ctx * @returns {DoctorCheck} */ @@ -3061,10 +3070,23 @@ export function checkComputerIntegrations(ctx) { const used = rest.filter(c => !c.incompatible && loaded.has(c.name)); const skipped = rest.filter(c => c.incompatible); const failed = rest.filter(c => !c.incompatible && !loaded.has(c.name)); + /** @type {Map} the issue messages of each package */ + const issuesOf = new Map(); + for (const issue of ctx.computerIntegrationIssues ?? []) { + issuesOf.set(issue.package, [ + ...(issuesOf.get(issue.package) ?? []), + issue.message, + ]); + } + const withIssues = used.filter(c => issuesOf.has(c.name)); const notes = [ used.length > 0 ? `Used outside a project: ${used.map(label).join(', ')}.` : '', + ...withIssues.map(c => { + const messages = issuesOf.get(c.name) ?? []; + return `${label(c)} has ${messages.length} integration issue${messages.length === 1 ? '' : 's'}: ${messages.join(' ')}`; + }), ...shadowed.map( c => `${label(c)} is not used here: this folder loads its own copy of ${c.name}.`, @@ -3081,11 +3103,28 @@ export function checkComputerIntegrations(ctx) { `run \`${formatCliCommand(`astryx doctor integration validate ${c.name}`, ctx.cwd)}\``, ), ]; + // The issues are in the package's own files: its maintainer fixes them, so + // anyone else needs a newer release. + const advice = withIssues.map(c => { + const one = (issuesOf.get(c.name) ?? []).length === 1; + const command = ctx.integrationUpdate?.(c.name) ?? null; + const how = command + ? ` To get one, run \`${command}\`.` + : ctx.integrationsUpdateWithTool + ? ' It updates with the tool that runs this CLI.' + : ''; + return `If you maintain ${c.name}, the ${one ? 'fix in the issue is' : 'fixes in the issues are'} yours. Otherwise, a newer release of ${c.name} needs to fix ${one ? 'it' : 'them'}.${how}`; + }); + const fix = [ + ...(fixes.length > 0 ? [`To fix: ${fixes.join('; ')}.`] : []), + ...advice, + ].join(' '); return { ...base, - status: skipped.length + failed.length > 0 ? 'warn' : 'pass', + status: + withIssues.length + skipped.length + failed.length > 0 ? 'warn' : 'pass', message: notes.join(' '), - ...(fixes.length > 0 ? {fix: `To fix: ${fixes.join('; ')}.`} : {}), + ...(fix ? {fix} : {}), }; } diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjs index c84423dc2fc1e..a604884679d62 100644 --- a/packages/cli/api/doctor/doctor.test.mjs +++ b/packages/cli/api/doctor/doctor.test.mjs @@ -36,6 +36,7 @@ import { checkCoreStylesheets, checkPackageManager, checkComputerIntegrationsAvailable, + checkComputerIntegrations, } from './doctor.mjs'; import {installCommandFor} from './_adapter.mjs'; import {formatCliCommand} from '../../foundation/env/package-manager.mjs'; @@ -537,6 +538,77 @@ describe('the command that adds an integration installed for the computer', () = }); }); +describe('checkComputerIntegrations outside a project', () => { + const widgets = /** @type {any} */ ({ + name: '@acme/widgets', + version: '1.0.0', + }); + const ctx = ( + /** @type {any[]} */ issues, + /** @type {any} */ update = null, + withTool = false, + ) => + /** @type {any} */ ({ + cwd: os.tmpdir(), + computerIntegrations: [widgets], + loadedComputerIntegrations: ['@acme/widgets'], + computerIntegrationIssues: issues, + integrationUpdate: update, + integrationsUpdateWithTool: withTool, + }); + const thing = { + package: '@acme/widgets', + severity: 'warning', + message: + 'Component source "Thing.tsx" has no same-stem metadata file Thing.doc.mjs, so Astryx ignores it.', + }; + + it('passes for an integration it uses whose contributions have no issues', () => { + expect(checkComputerIntegrations(ctx([]))).toMatchObject({ + status: 'pass', + message: 'Used outside a project: @acme/widgets@1.0.0.', + }); + }); + + // The everyday commands point at doctor for these issues + // (integration-warnings.mjs), so doctor names them. + it('warns and names each issue in the contributions of an integration it uses', () => { + const c = checkComputerIntegrations( + ctx([thing], (/** @type {string} */ name) => `npm i -g ${name}@latest`), + ); + expect(c.status).toBe('warn'); + expect(c.message).toBe( + 'Used outside a project: @acme/widgets@1.0.0. @acme/widgets@1.0.0 has 1 integration issue: Component source "Thing.tsx" has no same-stem metadata file Thing.doc.mjs, so Astryx ignores it.', + ); + expect(c.fix).toBe( + 'If you maintain @acme/widgets, the fix in the issue is yours. Otherwise, a newer release of @acme/widgets needs to fix it. To get one, run `npm i -g @acme/widgets@latest`.', + ); + }); + + it("counts several issues, and in a tool's package set says the tool updates it", () => { + const c = checkComputerIntegrations( + ctx( + [thing, {...thing, message: 'Template "x" names no source.'}], + null, + true, + ), + ); + expect(c.message).toContain( + '@acme/widgets@1.0.0 has 2 integration issues: ', + ); + expect(c.fix).toBe( + 'If you maintain @acme/widgets, the fixes in the issues are yours. Otherwise, a newer release of @acme/widgets needs to fix them. It updates with the tool that runs this CLI.', + ); + }); + + it('names no update step where none can be named, as under Volta', () => { + const c = checkComputerIntegrations(ctx([thing], () => null)); + expect(c.fix).toBe( + 'If you maintain @acme/widgets, the fix in the issue is yours. Otherwise, a newer release of @acme/widgets needs to fix it.', + ); + }); +}); + describe('checkInstallGuidance', () => { it('is left out when no integration gives guidance', () => { expect(checkInstallGuidance({cwd: mkProject({}), integrations: [{name: '@acme/a'}]})).toBeNull(); diff --git a/packages/cli/assets/docs/tree/computer-integrations.doc.mjs b/packages/cli/assets/docs/tree/computer-integrations.doc.mjs index 05699f74c5146..766ddb19db11c 100644 --- a/packages/cli/assets/docs/tree/computer-integrations.doc.mjs +++ b/packages/cli/assets/docs/tree/computer-integrations.doc.mjs @@ -73,7 +73,7 @@ export const docs = { type: 'list', style: 'unordered', items: [ - 'Outside a project, `{@command doctor}` lists the global integrations it uses and warns about each it skips.', + 'Outside a project, `{@command doctor}` lists the global integrations it uses, warns about each it skips, and names the issues in the files of each it uses, except issues that need a comparison with Core components.', 'Inside a project, `{@command doctor}` and `{@command discover}` list the ones the project could add.', ], }, diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjs index 57edd1d382d3b..7f6791b7ec678 100644 --- a/packages/cli/clients/cli/commands/doctor.doc.mjs +++ b/packages/cli/clients/cli/commands/doctor.doc.mjs @@ -23,7 +23,7 @@ export const doc = { "the docs the CLI reads, the newest release the computer knows of, with the install and upgrade commands when the project's release is older, and every `astryx` command on the search path, warning when the first one is not the Astryx CLI or predates the hand-off. Loading astryx.config runs that file's code. " + 'The `integration` subcommands provide authoring checks for one integration package. ' + 'Outside a project it checks the computer instead: the Node version, the release that answered, ' + - "the newest release this computer knows of, with the command that upgrades the CLI installed for the computer when it is older, the astryx commands on the search path, the integrations installed for the computer (warning about one it skips), and whether the computer-level agent text (`{@command init --user}`) is present, matches this release, was edited, or is turned off (info only); when that text names `astryx` and no `astryx` command is on the search path, apart from a package runner's own copy, it says so and names the install step the text records, or npm's when it records none. " + + "the newest release this computer knows of, with the command that upgrades the CLI installed for the computer when it is older, the astryx commands on the search path, the integrations installed for the computer (warning about one it skips, cannot load, or finds issues in), and whether the computer-level agent text (`{@command init --user}`) is present, matches this release, was edited, or is turned off (info only); when that text names `astryx` and no `astryx` command is on the search path, apart from a package runner's own copy, it says so and names the install step the text records, or npm's when it records none. " + 'It never fails a check because the folder has no project.', fn: 'doctor', subcommands: ['integration'], diff --git a/packages/cli/foundation/discovery/component-replacement.mjs b/packages/cli/foundation/discovery/component-replacement.mjs index 48d080f4a4a74..dd6e1231e930e 100644 --- a/packages/cli/foundation/discovery/component-replacement.mjs +++ b/packages/cli/foundation/discovery/component-replacement.mjs @@ -106,6 +106,19 @@ function packageJsonOf(integration) { } } +/** + * The findings that compare a component with Core's components: a + * replacement target Core does not have, two replacements of one Core + * component, and a component named like a Core one. Without a Core they + * cannot be judged. + * @type {ReadonlySet} + */ +export const CORE_COMPARISON_CODES = new Set([ + 'missing_component_replacement_target', + 'ambiguous_component_replacement', + 'shadowed_component_name', +]); + /** * Whether a package's declared CLI range turns its component replacements on. * @param {any} pkg package.json diff --git a/packages/cli/foundation/integrations/integration-warnings.mjs b/packages/cli/foundation/integrations/integration-warnings.mjs index 826426667da89..667ea756ccc3d 100644 --- a/packages/cli/foundation/integrations/integration-warnings.mjs +++ b/packages/cli/foundation/integrations/integration-warnings.mjs @@ -23,6 +23,17 @@ import {validateLoadedIntegration} from './validate-contributions.mjs'; import {formatCliCommand} from '../env/package-manager.mjs'; +/** + * Whether the nudge counts `issue` and points to doctor for it. A provider + * conflict carries the specific message that `doctor integration validate` + * would not explain, so the nudge prints it instead. + * @param {{code: string}} issue + * @returns {boolean} + */ +export function pointsToDoctor(issue) { + return issue.code !== 'duplicate_provider'; +} + /** * For each configured (already-loaded) integration, compute its issues using * the shared integration validators and, if any exist, print exactly @@ -48,9 +59,7 @@ export async function warnOnIntegrationIssues(source, {json = false} = {}) { if (fromProject) { const issues = await source.issues(); for (const issue of issues) { - // A provider-conflict issue carries the specific message that - // `doctor integration validate` would not explain. Print it directly. - if (issue.code === 'duplicate_provider') { + if (!pointsToDoctor(issue)) { console.error(`Warning: ${issue.message}`); continue; } diff --git a/packages/cli/foundation/release/notices.mjs b/packages/cli/foundation/release/notices.mjs index 033327b73b4e4..ae0e43361b6ba 100644 --- a/packages/cli/foundation/release/notices.mjs +++ b/packages/cli/foundation/release/notices.mjs @@ -255,13 +255,61 @@ function isBehind(version, newest) { * @returns {string} */ export function globalUpgradeCommand(cliRoot, where = {}) { - let at = cliRoot; + return globalInstallCommand(cliRoot, LATEST, where); +} + +/** + * The command that updates the package `name` installed beside the CLI + * installed for the computer at `cliRoot`, such as an integration installed + * for the computer (spec AST-081 FR12), by the package manager of the folder + * that holds them. Null for one of Astryx's own packages, which follows the + * CLI's releases (npm's `latest` tag of a canary-only one is a placeholder), + * and under Volta, which installs each package in a folder of its own. + * @param {string} cliRoot the CLI package's folder + * @param {string} name + * @param {{execPath?: string, home?: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv}} [where] + * @returns {string | null} + */ +export function globalUpdateBesideCli(cliRoot, name, where = {}) { + if (officialPackages().some(pkg => pkg.name === name)) return null; + if (isVoltaPath(realOrGiven(cliRoot))) return null; + return globalInstallCommand(cliRoot, `${name}@latest`, where); +} + +/** + * `p` with its links resolved, or as given when it cannot be read. + * @param {string} p + * @returns {string} + */ +function realOrGiven(p) { try { - at = fs.realpathSync(cliRoot); + return fs.realpathSync(p); } catch { - // Read the path as given. + return p; } - if (/[\\/]\.volta[\\/]/iu.test(at)) return `volta install ${LATEST}`; +} + +/** + * Whether the real path `at` is in a folder Volta installed. + * @param {string} at + * @returns {boolean} + */ +function isVoltaPath(at) { + return /[\\/]\.volta[\\/]/iu.test(at); +} + +/** + * The command that installs `spec` into the folder that holds the CLI + * installed for the computer at `cliRoot`, by that folder's package manager, + * as {@link globalUpgradeCommand} names the CLI. + * @param {string} cliRoot the CLI package's folder + * @param {string} spec the package and version, as `@acme/widgets@latest` + * @param {{execPath?: string, home?: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv}} [where] + * @returns {string} + */ +function globalInstallCommand(cliRoot, spec, where = {}) { + const at = realOrGiven(cliRoot); + if (isVoltaPath(at)) return `volta install ${spec}`; const { home = os.homedir(), platform = process.platform, @@ -270,18 +318,16 @@ export function globalUpgradeCommand(cliRoot, where = {}) { const global = globalFolderOf(at, {home, platform, env}); // Each reads the same settings that named its global folder, so its plain // command reinstalls into that folder. - if (global?.manager === 'bun') return `bun add -g ${LATEST}`; - if (global?.manager === 'yarn') return `yarn global add ${LATEST}`; + if (global?.manager === 'bun') return `bun add -g ${spec}`; + if (global?.manager === 'yarn') return `yarn global add ${spec}`; if ( global?.manager === 'pnpm' || /[\\/]pnpm[\\/]|[\\/]global[\\/]v?\d+[\\/]/iu.test(at) ) { - return `pnpm add -g ${LATEST}`; + return `pnpm add -g ${spec}`; } const prefix = npmOwnPrefix(at, where); - return prefix - ? `npm i -g --prefix ${prefix} ${LATEST}` - : `npm i -g ${LATEST}`; + return prefix ? `npm i -g --prefix ${prefix} ${spec}` : `npm i -g ${spec}`; } /** diff --git a/packages/cli/foundation/release/notices.test.mjs b/packages/cli/foundation/release/notices.test.mjs index 12711fab0779e..c8009bdc30ba6 100644 --- a/packages/cli/foundation/release/notices.test.mjs +++ b/packages/cli/foundation/release/notices.test.mjs @@ -16,6 +16,7 @@ import { NOTICE_INTERVAL_MS, availableLine, globalBehind, + globalUpdateBesideCli, globalUpgradeCommand, noticeLines, oldGlobalCommand, @@ -330,6 +331,45 @@ describe('the lines', () => { }); }); +describe('globalUpdateBesideCli', () => { + const linux = { + execPath: '/usr/bin/node', + home: '/home/a', + platform: /** @type {const} */ ('linux'), + env: {}, + }; + + it('updates a package beside the CLI with the package manager and prefix that hold the CLI', () => { + expect( + globalUpdateBesideCli( + '/home/a/.npm-global/lib/node_modules/@astryxdesign/cli', + '@acme/widgets', + linux, + ), + ).toBe('npm i -g --prefix ~/.npm-global @acme/widgets@latest'); + }); + + it("names no command for one of Astryx's own packages, which follows the CLI's releases", () => { + expect( + globalUpdateBesideCli( + '/home/a/.npm-global/lib/node_modules/@astryxdesign/cli', + '@astryxdesign/lab', + linux, + ), + ).toBeNull(); + }); + + it('names no command under Volta, which keeps each package in a folder of its own', () => { + expect( + globalUpdateBesideCli( + '/home/a/.volta/tools/image/packages/@astryxdesign/cli/lib/node_modules/@astryxdesign/cli', + '@acme/widgets', + linux, + ), + ).toBeNull(); + }); +}); + describe('globalBehind and projectLag', () => { it('need a completed check, and never report a current, newer, or prerelease version', () => { const self = { diff --git a/packages/cli/test/global-local.rows-16-39.test.mjs b/packages/cli/test/global-local.rows-16-39.test.mjs index 49e8136433639..2dddd9699091f 100644 --- a/packages/cli/test/global-local.rows-16-39.test.mjs +++ b/packages/cli/test/global-local.rows-16-39.test.mjs @@ -28,6 +28,7 @@ import { writeJson, } from '../test-utils/release-fixtures.mjs'; import {installPlaceOf} from '../foundation/release/choose.mjs'; +import {COMPONENT_REPLACES_CLI} from '../foundation/integrations/cli-requirement.mjs'; import {relativeWithin, samePath} from '../foundation/fs/path-compare.mjs'; import {userCacheDir} from '../foundation/env/user-dirs.mjs'; import {astryxCommandsOnSearchPath} from '../foundation/env/search-path.mjs'; @@ -626,6 +627,96 @@ describe.skipIf(!POSIX)( status: 'pass', message: 'Used outside a project: @acme/widgets@1.0.0.', }); + // One that validly replaces a Core component: doctor reads no Core + // outside a project, so it leaves that comparison to the commands that + // carry one, and reports no issue for it. + const nav = acmeWidgets(path.resolve(g.dir, '..', '..', '..'), { + topic: 'nav-guide', + name: '@acme/nav', + peers: {'@astryxdesign/cli': `>=${COMPONENT_REPLACES_CLI}`}, + manifest: + "export default {docs: './docs', components: './components'};\n", + }); + fs.mkdirSync(path.join(nav, 'components'), {recursive: true}); + fs.writeFileSync( + path.join(nav, 'components', 'AcmeSideNav.doc.mjs'), + `export default ${JSON.stringify({ + type: 'component', + name: 'AcmeSideNav', + displayName: 'AcmeSideNav', + import: '@acme/nav/components/AcmeSideNav', + replaces: 'SideNav', + keywords: ['acme'], + usage: {description: 'AcmeSideNav for Acme apps.'}, + props: [], + })};\n`, + ); + fs.writeFileSync( + path.join(nav, 'components', 'AcmeSideNav.tsx'), + 'export function AcmeSideNav() {\n return null;\n}\n', + ); + const withNav = JSON.parse( + run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout, + ).data.checks.find( + (/** @type {any} */ c) => c.id === 'computer-integrations', + ); + expect(withNav.message).toContain('@acme/nav@1.0.0'); + expect(withNav.status).toBe('pass'); + // One whose contributions have an issue: the everyday commands point + // at doctor for it, and doctor names it. + const broken = acmeWidgets(path.resolve(g.dir, '..', '..', '..'), { + topic: 'broken-guide', + name: '@acme/broken', + manifest: + "export default {docs: './docs', components: './components'};\n", + }); + fs.mkdirSync(path.join(broken, 'components'), {recursive: true}); + fs.writeFileSync( + path.join(broken, 'components', 'Thing.tsx'), + 'export function Thing() {\n return null;\n}\n', + ); + expect(run(g.bin, ['discover'], {cwd: empty, pc}).stderr).toContain( + 'Warning: @acme/broken has 1 integration issue(s). Run: astryx doctor', + ); + const after = JSON.parse( + run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout, + ).data.checks.find( + (/** @type {any} */ c) => c.id === 'computer-integrations', + ); + expect(after.status).toBe('warn'); + expect(after.message).toContain( + '@acme/broken@1.0.0 has 1 integration issue: Component source "Thing.tsx" has no same-stem metadata file Thing.doc.mjs', + ); + expect(after.message).not.toContain('@acme/nav@1.0.0 has'); + expect(after.fix).toContain( + 'Otherwise, a newer release of @acme/broken needs to fix it.', + ); + expect(after.fix).toContain('@acme/broken@latest'); + // One whose template replaces a template that Core does not have. + // Core's templates come with the CLI, so doctor names this issue too. + const tpl = acmeWidgets(path.resolve(g.dir, '..', '..', '..'), { + topic: 'tpl-guide', + name: '@acme/tpl', + manifest: + "export default {docs: './docs', templates: './templates'};\n", + }); + fs.mkdirSync(path.join(tpl, 'templates'), {recursive: true}); + fs.writeFileSync( + path.join(tpl, 'templates', 'acme-shell.doc.mjs'), + "export default {type: 'page', name: 'Acme shell', description: 'Acme app shell.', replaces: 'no-such-template'};\n", + ); + fs.writeFileSync( + path.join(tpl, 'templates', 'acme-shell.tsx'), + 'export default function AcmeShell() {\n return null;\n}\n', + ); + const withTpl = JSON.parse( + run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout, + ).data.checks.find( + (/** @type {any} */ c) => c.id === 'computer-integrations', + ); + expect(withTpl.status).toBe('warn'); + expect(withTpl.message).toContain('@acme/tpl@1.0.0 has'); + expect(withTpl.message).toContain('which is not a Core template id.'); }); it("G36 inside a project: an integration installed for the computer adds nothing, and discover and doctor list it as available with the project's install command", () => { From 5fb29adf57e42c2d682ad4d544aa7ce749146064 Mon Sep 17 00:00:00 2001 From: Joey <17398284+josephfarina@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:00:56 -0800 Subject: [PATCH 4/4] fix(cli): the commands that write the named destination keep --overwrite [skip ci] --- .changeset/template-refusal-cd-hint.md | 2 +- packages/cli/api/template/copy/copy.mjs | 13 +++--- .../commands/template.path-safety.test.mjs | 41 +++++++++++++++++++ 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/.changeset/template-refusal-cd-hint.md b/.changeset/template-refusal-cd-hint.md index 5ee9d2566bdde..453a1bfe9ca9d 100644 --- a/.changeset/template-refusal-cd-hint.md +++ b/.changeset/template-refusal-cd-hint.md @@ -2,6 +2,6 @@ '@astryxdesign/cli': patch --- -[feat] When `astryx template ` refuses the destination of a Core template that no integration replaces, outside the project (an absolute path, or one that leaves it through `..`), it also names the command that writes that same destination: a change to the nearest folder of it that exists, then the template command with the path from there, printed with the CLI invocation for that folder. A `..` path used to get the refusal with no command to run; it now gets the same commands as an absolute one. A `..` path that lands in the system temp folder is still not a scratch copy; the refusal names its absolute path, which takes one. +[feat] When `astryx template ` refuses the destination of a Core template that no integration replaces, outside the project (an absolute path, or one that leaves it through `..`), it also names the command that writes that same destination: a change to the nearest folder of it that exists, then the template command with the path from there, printed with the CLI invocation for that folder. When `--overwrite` was given, that command and the scratch-copy command keep it, so they do not refuse a second time; the suggested place inside the project is another file and never gets it. A `..` path used to get the refusal with no command to run; it now gets the same commands as an absolute one. A `..` path that lands in the system temp folder is still not a scratch copy; the refusal names its absolute path, which takes one. @josephfarina diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs index cd72a05668b6a..97cde9817b118 100644 --- a/packages/cli/api/template/copy/copy.mjs +++ b/packages/cli/api/template/copy/copy.mjs @@ -133,6 +133,12 @@ export function templateCopy( scratchPath || replaced || pkgOf(match) !== CORE_PACKAGE_NAME ? null : fromNearestFolder(path.resolve(cwd, fileTarget)); + // A command that writes the destination the caller named keeps + // `--overwrite`, so it does not refuse a second time. The place inside + // the project is another file, which it never overwrites unasked. + const sameWrite = (/** @type {string} */ destination) => + `${command} ${quoteCommandArgument(destination)}` + + (overwrite ? ' --overwrite' : ''); throw new AstryxError( `Invalid template target path "${given}": it is outside the project root (${path.resolve(cwd)}). ` + (scratchPath @@ -148,7 +154,7 @@ export function templateCopy( ...(scratchPath ? [ { - name: `${command} ${quoteCommandArgument(scratchPath)}`, + name: sameWrite(scratchPath), reason: 'take a scratch copy in the system temp folder', }, ] @@ -156,10 +162,7 @@ export function templateCopy( ...(there ? [ { - name: commandInFolder( - there.dir, - `${command} ${quoteCommandArgument(there.path)}`, - ), + name: commandInFolder(there.dir, sameWrite(there.path)), reason: `write the ${match.type} where you named it, from its folder`, }, ] diff --git a/packages/cli/clients/cli/commands/template.path-safety.test.mjs b/packages/cli/clients/cli/commands/template.path-safety.test.mjs index 182483cec8cbe..aa7e57aef2280 100644 --- a/packages/cli/clients/cli/commands/template.path-safety.test.mjs +++ b/packages/cli/clients/cli/commands/template.path-safety.test.mjs @@ -272,6 +272,47 @@ describe('template path safety', () => { }, ); + it.skipIf(process.platform === 'win32')( + 'keeps `--overwrite` in the command that writes the named path, so it does not refuse again', + async () => { + const root = fs.realpathSync(tmpDir); + const cwd = path.join(root, 'project'); + const elsewhere = path.join(root, 'elsewhere'); + const given = path.join(elsewhere, 'pages', 'blank.tsx'); + fs.mkdirSync(cwd, {recursive: true}); + fs.mkdirSync(path.dirname(given), {recursive: true}); + fs.writeFileSync(given, 'old\n'); + const before = process.env.HOME; + process.env.HOME = path.join(root, 'home'); + try { + const err = await templateApi('blank', { + targetPath: given, + cwd, + overwrite: true, + }).catch(e => e); + expect(err.code).toBe('ERR_PATH_TRAVERSAL'); + // The place inside the project is another file: no `--overwrite`. + expect(err.suggestions[0].name).toBe( + 'astryx template blank src/pages/blank.tsx', + ); + expect(err.suggestions[1].name).toBe( + `cd ${path.dirname(given)} && astryx template blank ./blank.tsx --overwrite`, + ); + + // The named command, run from that folder, replaces the file. + const written = await templateApi('blank', { + targetPath: './blank.tsx', + cwd: path.dirname(given), + overwrite: true, + }); + expect(written.data.fileName).toBe('blank.tsx'); + expect(fs.readFileSync(given, 'utf8')).not.toBe('old\n'); + } finally { + process.env.HOME = before; + } + }, + ); + it('names no folder to run from when only the disk root exists', async () => { const cwd = path.join(tmpDir, 'project'); fs.mkdirSync(cwd, {recursive: true});