An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): find Core and configured integrations from any folder in a project (#7492)
Joeycb489ffbcc87
diff --git a/.changeset/cli-find-core-from-any-folder.md b/.changeset/cli-find-core-from-any-folder.mdnew file mode 100644index 0000000000..194964d844--- /dev/null+++ b/.changeset/cli-find-core-from-any-folder.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] The CLI finds the project's `@astryxdesign/core` from any folder inside the project. `component`, `hook`, `build`, `search`, `swizzle`, `theme targets` and `doctor` still search the folders they searched before, and past them continue up to the workspace root of the nearest folder whose package.json declares an Astryx package. They now work five or more folders deep, in workspace members whose Core the workspace installs at its root, and in Yarn Plug'n'Play projects. `upgrade --from` run from any folder in a project upgrades that project, the nearest folder whose package.json declares an Astryx package or that an Astryx workspace lists, found without passing a repository root or counting the home folder: it scans the project's `src` by default, reads a `--path` you type from the folder you ran in, names the files in its `--json` result relative to that folder, and refreshes the project's agent docs. It targets only the project's own Core: the one in its `node_modules`, or for a member its workspace lists, the one the workspace installs. With no such project, `upgrade` reads only the current folder, as before. It names the project root and the source folder it scans before it changes anything. An `upgrade` run in a folder that installs Core but declares no Astryx package now upgrades the Astryx project above it instead of that folder alone: a compatible fix under `architecture:cli-surface` INV10b, since such a folder was never a separate upgrade root. To keep a sub-folder that installs Core its own project, declare an Astryx package in that folder's package.json. A `packages/core` folder that holds another package is no longer read as Core, and an integration named in `astryx.config` now loads when the workspace installs it at its root, as an autolinked one already did.++@josephfarinadiff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex 63846caf3e..bdbe193c75 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -273,6 +273,17 @@ validate` MUST warn on a PascalCase `.tsx` at the top of the components rootInputs whose writes stay inside the root keep working. Refusing one of them,moving outputs instead of refusing, or confining an operation that no currentrecord confines is classified like any other change.+- **INV10b — An upgrade acts on the project it runs in; a folder below that+ project is never a separate root.** `astryx upgrade` operates on the project+ `spec:AST-040` FR9 finds: the nearest folder at or above where it runs whose+ `package.json` declares an Astryx package, or that an Astryx workspace lists.+ A folder that installs `@astryxdesign/core` but declares no Astryx package+ and is not a listed workspace member is not a supported upgrade root: an+ upgrade run there that migrates only that folder leaves the rest of the+ project on the old release, so a caller who relied on it is not a released+ victim (`spec:AST-017` FR54). Acting on the project above such a folder is a+ compatible `[fix]` and patch-eligible. A folder that declares an Astryx+ package is its own project, so a run there operates on that folder.- **INV11 — A broken integration degrades a command run, it does not failit.** The `Project` seam loads each integration independently and recordsthe failure, and the command's own work proceeds without that integration's@@ -790,6 +801,22 @@ Rejected: copying every report to the integration's own `issuesUrl`automatically (reports land in places nobody picked); letting the agent pickthe destination.+### DEC-10 — An upgrade migrates the whole project it runs in++**Decider:** `josephfarina`, `2026-10-21`++An upgrade that acts on one folder of a project reads none of the project's+configuration, refreshes none of its agent docs, and migrates only part of+its source, leaving the project half on each release with nothing to say so.+`spec:AST-040` FR9 makes the project the unit of an upgrade, and a folder that+installs Core without declaring it is a hoisted install or a stray+`node_modules`, not an app of its own, so following FR9 there is a `[fix]`+(INV10b). The boundary is narrow: a folder that declares an Astryx package+keeps its own upgrade.++Rejected: treating every folder with an installed Core as a project (a+workspace member then migrates against a Core its workspace does not use).+## Verification| Invariant | Evidence | Failure signal |@@ -800,6 +827,7 @@ the destination.| INV4 | `clients/cli/formatters/index.test.mjs`, type tests | `emit` accepts a bare string, or output varies between pipe and TTY. || INV6 | `pnpm check:cli-structure` | A command's file or its doc is missing, or sits at the wrong path. || INV8 | `clients/cli/cli-exit-codes.test.mjs` | The same condition exits differently with and without `--json`. |+| INV10b | `api/upgrade/run/run.test.mjs` (a folder that installs Core without declaring it upgrades the project above it; a member its workspace lists and one that declares Astryx keep their own), `clients/cli/commands/upgrade.subfolder-path.test.mjs` | A folder that installs Core without declaring Astryx upgrades only itself, or a declaring folder or a listed member upgrades the project above it. || INV14 | `foundation/integrations/autolink.test.mjs`, `foundation/config/project.test.mjs` | An undeclared package contributes, or configured/local precedence changes. || INV15 | `api/integration/add-contribution.test.mjs`, `clients/cli/commands/integration-authoring.test.mjs` | Dry-run/write paths differ, a writer clobbers bytes, or the new contribution is not discoverable. || INV16 | `foundation/integrations/manifest-writer.test.mjs`, `api/integration/add-contribution.test.mjs` | A writer invents package policy, replaces an author entry, or local bytes lose precedence. |diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex 195318416d..3593b0f325 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -1317,8 +1317,12 @@ describe('a configured integration that cannot load fails the gate', () => {'astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",};- /** Run doctor on a project under the working directory. */- async function report(files) {+ /**+ * Run doctor on a project under the working directory, in its folder `at`.+ * @param {Record<string, string>} files+ * @param {string} [at]+ */+ async function report(files, at = '.') {const dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-gate-'));tmpDirs.push(dir);for (const [rel, content] of Object.entries(files)) {@@ -1326,7 +1330,7 @@ describe('a configured integration that cannot load fails the gate', () => {fs.mkdirSync(path.dirname(abs), {recursive: true});fs.writeFileSync(abs, content);}- const {checks, summary} = (await doctor({cwd: dir})).data;+ const {checks, summary} = (await doctor({cwd: path.join(dir, at)})).data;return {by: Object.fromEntries(checks.map(c => [c.id, c])), summary};}@@ -1354,6 +1358,27 @@ describe('a configured integration that cannot load fails the gate', () => {SLOW,);+ it(+ 'passes in a workspace member whose configured integration is hoisted to the root',+ async () => {+ const {by} = await report(+ {+ 'package.json': JSON.stringify({name: 'root', private: true, workspaces: ['apps/*']}),+ ...CORE_STUB,+ ...widgets(),+ 'apps/web/package.json': '{"name":"web"}',+ 'apps/web/astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",+ },+ 'apps/web',+ );+ expect(by['configured-integrations'].status).toBe('pass');+ expect(by['configured-integrations'].message).toBe(+ '1 integration named in astryx.config loaded: @acme/widgets.',+ );+ },+ SLOW,+ );+it('counts the package being authored when its own config names it',async () => {diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex 3a0ac6f949..a800c5ffb3 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -12,7 +12,7 @@* - validateLocalIntegration(cwd) — the package rooted at `cwd` (nearest* package.json + sibling astryx.integration.{ts,mjs,js}).* - validateInstalledIntegration(spec, cwd) — an installed package resolved- * from `cwd`/node_modules.+ * from the node_modules chain at or above `cwd`.** Both return a { found, name, version, manifestFile, issues } result. `found`* is false only for the no-manifest local case, which is guidance (not an@@ -52,7 +52,7 @@ import {import {findManifestPaths,loadManifest,- resolvePackageDir,+ resolveInstalledIntegrationDir,} from '../../foundation/integrations/integrations.mjs';// The on-disk contribution validators live in foundation: Project and// integration-warnings need them too, and foundation must not depend on api.@@ -595,20 +595,21 @@ function packageJsonFieldIssues(pkg, pkgJsonPath) {}/**- * Validate an INSTALLED integration package resolved from `cwd`/node_modules.+ * Validate an INSTALLED integration package: the nearest `node_modules/<spec>`+ * at or above `cwd`, resolved the way the project loads it.* @param {string} spec package name* @param {string} [cwd]* @returns {Promise<ValidateResult>}*/export async function validateInstalledIntegration(spec, cwd = process.cwd()) {- // resolvePackageDir throws (path-safety guard) on a spec with path segments,+ // The resolver throws (path-safety guard) on a spec with path segments,// `..`, or an absolute path. Every other malformed input to this command// degrades into a diagnostic — so catch it here and return an issue instead// of letting the throw escape to a raw stack (human) / generic ERR_UNKNOWN// (--json).let packageDir;try {- packageDir = resolvePackageDir(spec, cwd);+ packageDir = resolveInstalledIntegrationDir(spec, cwd);} catch (err) {return {found: true,diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex d958f9512c..b30a6675c8 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -44,7 +44,11 @@ import {quoteCommandArgument,} from '../../foundation/env/package-manager.mjs';import {isValidSemver, semverGt} from '../../foundation/env/semver.mjs';-import {CLI_ROOT} from '../../foundation/fs/paths.mjs';+import {+ CLI_ROOT,+ findAstryxProject,+ findProjectPackageOf,+} from '../../foundation/fs/paths.mjs';import {Project, providerLedgerOf} from '../../foundation/config/project.mjs';import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';import {resolveProviders} from '../../foundation/integrations/provider-resolution.mjs';@@ -84,26 +88,125 @@ const execFileAsync = promisify(execFile);*//**- * Detect the installed target version from node_modules.+ * Where an upgrade runs: the root of the Astryx project `cwd` belongs to, the+ * nearest folder at or above it whose package.json declares an Astryx+ * package or that an Astryx workspace lists as a member, so a run from any+ * folder inside a project upgrades that project exactly as a run from its+ * root does. Its source, config, agent docs and+ * protection declarations all live there. The search stops at a repository+ * root and ends at the home folder without counting it (see+ * `findAstryxProject`). A `path` the caller names, in any spelling (`./src`,+ * `src`, `src/`), is read from `cwd`, where they typed it. With no `path`,+ * the upgrade scans `./src` at the project root. With no Astryx project, the+ * upgrade runs in `cwd` as released versions did.+ * @param {UpgradeOptions} options+ * @param {string} cwd+ * @returns {{options: UpgradeOptions, cwd: string, origin?: string}} `origin`+ * is the folder the command ran in, when the project root is above it+ */+export function scopeToProject(options, cwd) {+ const here = path.resolve(cwd);+ const root = findAstryxProject(here) ?? here;+ if (root === here) return {options, cwd};+ const namedPath =+ options.path == null ? {} : {path: path.resolve(here, options.path)};+ return {options: {...options, ...namedPath}, cwd: root, origin: here};+}++/**+ * The result of an upgrade that ran at a project root above the folder the+ * command ran in, with its file paths made relative to that folder, so each+ * resolves from where the command ran: `modifiedFiles`, `agentDocs.files`, and+ * the `file` of each `protectedFiles`, `declinedCandidates` and `errors`+ * entry. The registry step names copied-composition paths from that folder+ * itself (see `reconcileRegistryCompositions`), so they pass through. A+ * result of a run at the project root is returned as it is.+ * @template {{type: string, data: object}} T+ * @param {T} result+ * @param {{cwd: string, origin?: string}} scope from `scopeToProject`+ * @returns {T}+ */+export function relativeToOrigin(result, {cwd: root, origin}) {+ if (origin == null) return result;+ /** @param {string} file */+ const rebase = file =>+ path.relative(origin, path.resolve(root, file)).split(path.sep).join('/') ||+ '.';+ /** @type {Record<string, any>} */+ const data = {...result.data};+ if (data.agentDocs) {+ data.agentDocs = {+ ...data.agentDocs,+ files: data.agentDocs.files.map(rebase),+ };+ }+ if (data.modifiedFiles) data.modifiedFiles = data.modifiedFiles.map(rebase);+ for (const key of ['protectedFiles', 'declinedCandidates', 'errors']) {+ if (data[key]) {+ data[key] = data[key].map(+ (/** @type {{file: string, declarations?: string[]}} */ entry) => ({+ ...entry,+ file: rebase(entry.file),+ ...(Array.isArray(entry.declarations)+ ? {declarations: entry.declarations.map(rebaseDeclaration(rebase))}+ : {}),+ }),+ );+ }+ }+ return /** @type {T} */ ({...result, data});+}++/**+ * The project-relative file a protection declaration names, and the text+ * around it: the ignore or attributes file that protects a file (and its+ * line), or the symbolic link on its path. Other declarations name no file.+ */+const DECLARATION_PATHS = [+ /^(excluded by )(.+?)(:\d+)?$/u,+ /^(linguist-(?:generated|vendored) in )(.+?)(:\d+)$/u,+ /^(symbolic link at )(.+)()$/u,+];++/**+ * A protection declaration with the file it names rebased, as `rebase` does+ * for result paths.+ * @param {(file: string) => string} rebase+ * @returns {(declaration: string) => string}+ */+function rebaseDeclaration(rebase) {+ return declaration => {+ for (const pattern of DECLARATION_PATHS) {+ const match = pattern.exec(declaration);+ if (match) return `${match[1]}${rebase(match[2])}${match[3] ?? ''}`;+ }+ return declaration;+ };+}++/**+ * Detect the installed target version: the Core the Astryx project of `cwd`+ * installed, in its own node_modules or, for a member its workspace lists, in+ * a folder up to the workspace root. The nearest folder wins, the current+ * name before the legacy one, then Yarn Plug'n'Play. A Core above a project+ * no workspace lists does not count, so a nested project that has not+ * installed its own reports nothing installed. With no Astryx project, only+ * the node_modules of `cwd` itself is read, as released versions did.* @param {string} cwd* @returns {{version: string, packageName: string}|null}*/export function detectInstalledTargetVersion(cwd) {- for (const packageName of ['@astryxdesign/core', '@xds/core']) {- const pkgPath = path.resolve(- cwd,- 'node_modules',- ...packageName.split('/'),- 'package.json',+ const found = findProjectPackageOf(cwd, ['@astryxdesign/core', '@xds/core']);+ if (!found) return null;+ try {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf-8'),);- try {- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));- if (pkg.version) return {version: pkg.version, packageName};- } catch {- // Missing/unreadable — try the next supported package name.- }+ return pkg.version ? {version: pkg.version, packageName: found.name} : null;+ } catch {+ // Unreadable package.json: no version to target.+ return null;}- return null;}/**@@ -284,10 +387,26 @@ export async function runPostCodemodHooks(hooks, context) {/*** @typedef {object} AgentDocsRefreshPlan* @property {string} cwd+ * @property {string} [origin] the folder the command ran in, when the upgrade+ * runs at a project root above it* @property {string|null} renderedBlock* @property {import('./upgrade.type.mjs').AgentDocsSummary} summary*/+/**+ * The advice to run `init`, phrased for where the command ran: when the+ * upgrade runs at a project root above that folder, it names the root, so the+ * agent docs are installed beside the project's package.json.+ * @param {string} cwd the folder the upgrade runs at+ * @param {string} [origin] the folder the command ran in+ * @returns {string}+ */+function initAdvice(cwd, origin) {+ const command = `\`${formatCliCommand('astryx init --features agents')}\``;+ if (origin == null) return command;+ return `${command} in ${path.relative(origin, cwd) || '.'} (the project root)`;+}+/*** Why upgrade leaves the agent docs of a project at the home folder or the* top of a settings folder, and what to do instead. init refuses the same@@ -308,7 +427,7 @@ function homeRefusalLine(err, state = 'stale') {* Apply-mode callers commit the prepared bytes only after codemods and hooks* succeed.*- * @param {{cwd: string, installedVersion: string, apply: boolean, fresh?: boolean}} ctx+ * @param {{cwd: string, installedVersion: string, apply: boolean, fresh?: boolean, origin?: string}} ctx* @returns {Promise<AgentDocsRefreshPlan>}*/export async function prepareAgentDocsRefresh({@@ -316,6 +435,7 @@ export async function prepareAgentDocsRefresh({installedVersion,apply,fresh = false,+ origin,}) {const initial = inspectAgentDocs(cwd, installedVersion);/** @type {import('./upgrade.type.mjs').AgentDocsSummary} */@@ -337,13 +457,13 @@ export async function prepareAgentDocsRefresh({if (!(err instanceof AgentDocsHomeError)) throw err;summary.action = 'error';logger.warn(homeRefusalLine(err, 'missing'));- return {cwd, renderedBlock: null, summary};+ return {cwd, origin, renderedBlock: null, summary};}summary.action = 'nudge-init';logger.warn(- `No Astryx agent-docs block found - AI agents have no component index. Run \`${formatCliCommand('astryx init --features agents')}\` to install it.`,+ `No Astryx agent-docs block found - AI agents have no component index. Run ${initAdvice(cwd, origin)} to install it.`,);- return {cwd, renderedBlock: null, summary};+ return {cwd, origin, renderedBlock: null, summary};}let renderedBlock;@@ -356,16 +476,18 @@ export async function prepareAgentDocsRefresh({summary.action = 'error';summary.files = initial.files.map(file => file.path);logger.warn(- `Could not render the expected agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,+ `Could not render the expected agent docs. Run ${initAdvice(cwd, origin)} to update them manually.`,);- return {cwd, renderedBlock: null, summary};+ return {cwd, origin, renderedBlock: null, summary};}const inspection = inspectAgentDocs(cwd, installedVersion, renderedBlock);summary.status = inspection.status;summary.fromVersions = inspection.blockVersions;summary.files = inspection.staleFiles;- if (inspection.status === 'current') return {cwd, renderedBlock, summary};+ if (inspection.status === 'current') {+ return {cwd, origin, renderedBlock, summary};+ }// A project at the home folder or the top of a settings folder is never// refreshed (INV31): the dry run says so, as --apply does, rather than@@ -376,7 +498,7 @@ export async function prepareAgentDocsRefresh({if (!(err instanceof AgentDocsHomeError)) throw err;summary.action = 'error';logger.warn(homeRefusalLine(err));- return {cwd, renderedBlock: null, summary};+ return {cwd, origin, renderedBlock: null, summary};}summary.action = 'would-refresh';@@ -385,7 +507,7 @@ export async function prepareAgentDocsRefresh({`Agent docs differ from the installed Astryx and integration configuration. Re-run with --apply to refresh (${summary.files.join(', ')}).`,);}- return {cwd, renderedBlock, summary};+ return {cwd, origin, renderedBlock, summary};}/**@@ -394,7 +516,7 @@ export async function prepareAgentDocsRefresh({* @returns {import('./upgrade.type.mjs').AgentDocsSummary}*/export function applyAgentDocsRefresh(plan) {- const {cwd, renderedBlock, summary} = plan;+ const {cwd, origin, renderedBlock, summary} = plan;if (summary.action !== 'would-refresh' || renderedBlock == null)return summary;@@ -413,7 +535,7 @@ export function applyAgentDocsRefresh(plan) {logger.log(`[ok] Agent docs refreshed -> ${written.join(', ')}`);} else {logger.warn(- `Agent docs look stale but couldn't be refreshed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,+ `Agent docs look stale but couldn't be refreshed. Run ${initAdvice(cwd, origin)} to reinstall the block.`,);}} catch (err) {@@ -425,7 +547,7 @@ export function applyAgentDocsRefresh(plan) {logger.warn(homeRefusalLine(err));} else {logger.warn(- `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,+ `Could not refresh agent docs. Run ${initAdvice(cwd, origin)} to update them manually.`,);}}diff --git a/packages/cli/api/upgrade/registry/registry.mjs b/packages/cli/api/upgrade/registry/registry.mjsindex 31b3215cf5..e792769cbb 100644--- a/packages/cli/api/upgrade/registry/registry.mjs+++ b/packages/cli/api/upgrade/registry/registry.mjs@@ -414,8 +414,9 @@ async function fetchLatestReceipt(/*** @param {string} receiptPath* @param {string} root+ * @param {string} [display] the folder reported paths are relative to*/-function loadInstalledReceipt(receiptPath, root) {+function loadInstalledReceipt(receiptPath, root, display = root) {let receipt;let receiptText;try {@@ -436,7 +437,7 @@ function loadInstalledReceipt(receiptPath, root) {}} catch (error) {throw new Error(- `Invalid receipt ${relativePath(receiptPath, root)}: ${error instanceof Error ? error.message : String(error)}`,+ `Invalid receipt ${relativePath(receiptPath, display)}: ${error instanceof Error ? error.message : String(error)}`,{cause: error},);}@@ -445,7 +446,7 @@ function loadInstalledReceipt(receiptPath, root) {const candidates = receiptFileCandidates(receipt, file).map(candidate => {if (registryContentHash(candidate.content) !== candidate.sha256) {throw new Error(- `Invalid receipt ${relativePath(receiptPath, root)}: stored hash does not match ${file.registryPath} (${candidate.format})`,+ `Invalid receipt ${relativePath(receiptPath, display)}: stored hash does not match ${file.registryPath} (${candidate.format})`,);}let sourcePath;@@ -458,7 +459,7 @@ function loadInstalledReceipt(receiptPath, root) {} catch (error) {if (error instanceof PathSafetyError) {throw new Error(- `Invalid receipt ${relativePath(receiptPath, root)}: ${error.message}`,+ `Invalid receipt ${relativePath(receiptPath, display)}: ${error.message}`,{cause: error},);}@@ -471,7 +472,7 @@ function loadInstalledReceipt(receiptPath, root) {);if (existing.length > 1) {throw new Error(- `Invalid receipt ${relativePath(receiptPath, root)}: multiple install variants exist for ${file.registryPath}`,+ `Invalid receipt ${relativePath(receiptPath, display)}: multiple install variants exist for ${file.registryPath}`,);}return existing[0] ?? candidates[0];@@ -483,12 +484,14 @@ function loadInstalledReceipt(receiptPath, root) {/*** @param {string} receiptPath* @param {string} root- * @param {{fetchImpl: typeof fetch, registryOrigin: string, expectedVersion?: string}} options+ * @param {{fetchImpl: typeof fetch, registryOrigin: string, expectedVersion?: string, display?: string}} options+ * `display` is the folder reported paths are relative to, `root` by default*/async function planReceipt(receiptPath, root, options) {+ const display = options.display ?? root;let installed;try {- installed = loadInstalledReceipt(receiptPath, root);+ installed = loadInstalledReceipt(receiptPath, root, display);} catch (error) {return {receiptPath,@@ -584,7 +587,7 @@ async function planReceipt(receiptPath, root, options) {oldReceiptText,};}- const displayPath = relativePath(sourcePath, root);+ const displayPath = relativePath(sourcePath, display);try {if (!fs.existsSync(sourcePath)) {plannedFiles.push({@@ -636,7 +639,7 @@ async function planReceipt(receiptPath, root, options) {const newFile = newReceiptFile? receiptFileForFormat(newReceipt, newReceiptFile, oldFile.format): null;- const displayPath = relativePath(oldFile.sourcePath, root);+ const displayPath = relativePath(oldFile.sourcePath, display);if (!newReceiptFile) {plannedFiles.push({id: oldFile.id,@@ -856,8 +859,12 @@ function publicAction(action, apply) {return action;}-/** @param {any} item @param {string} root @param {boolean} apply */-function publicItem(item, root, apply) {+/**+ * @param {any} item+ * @param {string} display the folder reported paths are relative to+ * @param {boolean} apply+ */+function publicItem(item, display, apply) {return {item: item.item,path: item.itemPath,@@ -870,7 +877,7 @@ function publicItem(item, root, apply) {action: publicAction(file.action, apply),...(file.message ? {message: file.message} : {}),...(file.action === 'conflict' && file.conflictPath- ? {conflictFile: relativePath(file.conflictPath, root)}+ ? {conflictFile: relativePath(file.conflictPath, display)}: {}),}),),@@ -968,13 +975,17 @@ function applyPlan(plan) {}/**+ * Reported paths are relative to the scanned source folder, or, when `origin`+ * names the folder the command ran in below the project root `cwd`, to that+ * folder, so they resolve from where the command ran.* @param {{apply?: boolean, path?: string}} options- * @param {{cwd?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]+ * @param {{cwd?: string, origin?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]*/export async function reconcileRegistryCompositions(options = {},{cwd = process.cwd(),+ origin,fetchImpl = globalThis.fetch,registryOrigin = PUBLIC_SHADCN_REGISTRY_ORIGIN,expectedVersion,@@ -998,6 +1009,7 @@ export async function reconcileRegistryCompositions(throw error;}+ const display = origin ?? root;const apply = options.apply ?? false;const receipts = discoverRegistryReceipts(root);const summary = emptySummary(apply);@@ -1019,6 +1031,7 @@ export async function reconcileRegistryCompositions(fetchImpl,registryOrigin,expectedVersion,+ display,}),);@@ -1031,7 +1044,7 @@ export async function reconcileRegistryCompositions(summary.invalid++;}}- recordItem(summary, publicItem(plan, root, apply), plan.action, apply);+ recordItem(summary, publicItem(plan, display, apply), plan.action, apply);if (!apply) continue;try {@@ -1119,13 +1132,17 @@ export function logRegistryCompositionSummary(summary) {}/**- * Standalone `astryx upgrade --registry` leaf.+ * Standalone `astryx upgrade --registry` leaf. `ctx.origin` is the folder the+ * command ran in, when `ctx.cwd` is the project root above it.* @param {{apply?: boolean, path?: string}} options- * @param {{cwd?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]+ * @param {{cwd?: string, origin?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]* @returns {Promise<import('../upgrade.type.mjs').UpgradeRegistryResponse>}*/export async function registryUpgrade(options = {}, ctx = {}) {const cwd = ctx.cwd ?? process.cwd();+ if (ctx.origin != null) {+ logger.log(`Project root: ${path.relative(ctx.origin, cwd) || '.'}`);+ }const installed = detectInstalledTargetVersion(cwd);const expectedVersion =ctx.expectedVersion ??diff --git a/packages/cli/api/upgrade/registry/registry.test.mjs b/packages/cli/api/upgrade/registry/registry.test.mjsindex 2af471a960..0530a9819c 100644--- a/packages/cli/api/upgrade/registry/registry.test.mjs+++ b/packages/cli/api/upgrade/registry/registry.test.mjs@@ -19,6 +19,8 @@ import {discoverRegistryReceipts,reconcileRegistryCompositions,} from './registry.mjs';+import {upgrade} from '../upgrade.mjs';+import {logger} from '../../logger.mjs';const ITEM = {name: 'example-button-basic',@@ -824,3 +826,86 @@ describe('registry composition upgrades', () => {expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');});});++describe('copied-composition paths name files from the folder the command ran in', () => {+ it('below the project root, and from the scanned source folder at the root', async () => {+ const {sourcePath} = seed({+ base: 'value = 1\n',+ current: 'value = local\n',+ });+ const fetchImpl = remote('value = upstream\n');+ const origin = path.join(project, 'apps', 'web');++ const [atRoot] = (await reconcile({}, {fetchImpl})).summary.items[0].files;+ const [below] = (await reconcile({}, {fetchImpl, origin})).summary.items[0]+ .files;++ expect(atRoot).toMatchObject({+ path: SOURCE_TARGET,+ conflictFile: `${SOURCE_TARGET}.astryx-conflict`,+ });+ expect(below).toMatchObject({+ path: `../../src/${SOURCE_TARGET}`,+ conflictFile: `../../src/${SOURCE_TARGET}.astryx-conflict`,+ });+ expect(path.resolve(origin, below.path)).toBe(sourcePath);+ });++ it('for an invalid receipt too', async () => {+ const value = receipt('base\n');+ value.files[0].sha256 = '0'.repeat(64);+ seed({base: 'base\n', receiptValue: value});+ const fetchImpl = remote('new\n');+ const origin = path.join(project, 'docs');++ const [atRoot] = (await reconcile({}, {fetchImpl})).summary.items;+ const [below] = (await reconcile({}, {fetchImpl, origin})).summary.items;++ expect(atRoot.message).toContain(`Invalid receipt ${RECEIPT_TARGET}:`);+ expect(below.message).toContain(+ `Invalid receipt ../src/${RECEIPT_TARGET}:`,+ );+ });++ it('through upgrade(), with --registry and in a run, which name the project root', async () => {+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({+ name: 'app',+ dependencies: {'@astryxdesign/core': '0.6.0'},+ }),+ );+ const core = path.join(project, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(+ path.join(core, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.0'}),+ );+ const frontend = path.join(project, 'frontend');+ fs.mkdirSync(frontend);+ seed({base: 'old\n'});+ vi.stubGlobal('fetch', remote('new\n'));+ const log = vi.spyOn(logger, 'log');+ try {+ const registry = await upgrade({registry: true}, {cwd: frontend});+ const run = await upgrade({from: '0.6.0'}, {cwd: frontend});+ const atRoot = await upgrade({registry: true}, {cwd: project});++ expect(registry.data.items[0].files[0].path).toBe(+ `../src/${SOURCE_TARGET}`,+ );+ expect(run.data.registryCompositions.items[0].files[0].path).toBe(+ `../src/${SOURCE_TARGET}`,+ );+ expect(atRoot.data.items[0].files[0].path).toBe(SOURCE_TARGET);+ expect(+ log.mock.calls.filter(([line]) =>+ String(line).startsWith('Project root:'),+ ),+ ).toEqual([['Project root: ..'], ['Project root: ..']]);+ } finally {+ vi.unstubAllGlobals();+ log.mockRestore();+ }+ });+});diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex 1fac4e94e7..c6f2d39ae0 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -115,10 +115,11 @@ function loadFileProtection(cwd) {* on failure. Progress is emitted through the shared `logger` (silent by default).** @param {import('../_adapter.mjs').UpgradeOptions} [options]- * @param {{cwd?: string}} [ctx]+ * @param {{cwd?: string, origin?: string}} [ctx] `origin` is the folder the+ * command ran in, when `cwd` is the project root above it* @returns {Promise<import('../upgrade.type.mjs').UpgradeStatusResponse | import('../upgrade.type.mjs').UpgradeRunResponse>}*/-export async function run(options = {}, {cwd = process.cwd()} = {}) {+export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {// Resolve the source dir against the API's cwd (not process.cwd()) so a// programmatic caller in another directory scans the right tree. Confine it to// cwd: --apply rewrites files in place, so a `..`-escaping or out-of-tree@@ -152,6 +153,12 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {const sourcePathFound = fs.existsSync(path_);const currentVersion = /** @type {string} */ (options.from);+ // Named first, so a run that stops on the Core lookup below still says which+ // folder it searched (spec:AST-040 FR12).+ if (origin != null) {+ logger.log(`Project root: ${path.relative(origin, cwd) || '.'}`);+ logger.log(`Source folder: ${path.relative(origin, path_) || '.'}`);+ }const installed = detectInstalledTargetVersion(cwd);if (!installed) {// Outside a project there is no version to install (spec AST-081 FR3).@@ -170,6 +177,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {{apply, path: path_},{cwd,+ origin,expectedVersion:installed.packageName === '@astryxdesign/core'? targetVersion@@ -192,6 +200,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {const registryResult = await reconcileCompositions();const agentDocsPlan = await prepareAgentDocsRefresh({cwd,+ origin,installedVersion: targetVersion,apply,});@@ -396,6 +405,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {// No codemods in range — safe to render agent docs from current state.const agentDocsPlan = await prepareAgentDocsRefresh({cwd,+ origin,installedVersion: targetVersion,apply,});@@ -671,6 +681,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {if (protectedFiles.length === 0) {const agentDocsPlan = await prepareAgentDocsRefresh({cwd,+ origin,installedVersion: targetVersion,apply,fresh: true,diff --git a/packages/cli/api/upgrade/run/run.test.mjs b/packages/cli/api/upgrade/run/run.test.mjsindex 5664de3a91..154e00905b 100644--- a/packages/cli/api/upgrade/run/run.test.mjs+++ b/packages/cli/api/upgrade/run/run.test.mjs@@ -3,18 +3,41 @@/*** @file Colocated tests for the upgrade.run leaf — the --path scan dir must be* confined to cwd (upgrade rewrites source in place with --apply, so an escaping- * or out-of-tree path must be rejected), and the receipt must say whether that- * dir existed at all.+ * or out-of-tree path must be rejected), the receipt must say whether that+ * dir existed at all, a run from any folder in a project upgrades that+ * project (the nearest folder whose package.json declares Astryx, never the+ * home folder) and names files relative to the folder it ran in, and the+ * target Core is the project's own.*/-import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import {upgrade} from '../upgrade.mjs';+import {relativeToOrigin} from '../_adapter.mjs';+import {logger} from '../../logger.mjs';+import {generateCompressedIndex} from '../../../foundation/agent-docs/agent-docs.mjs';const SLOW = 30_000;+/**+ * Run `fn` with `home` as the home folder.+ * @template T+ * @param {string} home @param {() => Promise<T>} fn+ * @returns {Promise<T>}+ */+async function withHome(home, fn) {+ const previous = process.env.HOME;+ process.env.HOME = home;+ try {+ return await fn();+ } finally {+ if (previous === undefined) delete process.env.HOME;+ else process.env.HOME = previous;+ }+}+function seedProject(dir) {fs.writeFileSync(path.join(dir, 'package.json'),@@ -95,3 +118,394 @@ describe('upgrade.run — sourcePathFound', () => {expect(res.data.sourcePathFound).toBe(true);}, SLOW);});++/** Core 0.7.0 renamed this prop; its codemod renames it on Typeahead. */+const OLD_PROP_SOURCE =+ "import {Typeahead} from '@astryxdesign/core';\n" ++ 'export const App = () => <Typeahead label="Fruit" emptySearchResultsText="None" />;\n';++/**+ * A project with Core 0.7.0 installed and src/App.tsx using a prop that 0.7.0+ * renamed.+ * @param {string} dir+ */+function seedOldPropProject(dir) {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({name: '@astryxdesign/core', version: '0.7.0'}));+ fs.mkdirSync(path.join(dir, 'src', 'l1', 'l2'), {recursive: true});+ fs.writeFileSync(path.join(dir, 'src', 'App.tsx'), OLD_PROP_SOURCE);+}++describe('upgrade.run — a run from a subfolder upgrades the project', () => {+ let dir;+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-scope-'));+ seedOldPropProject(dir);+ });+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++ const appSource = () => fs.readFileSync(path.join(dir, 'src', 'App.tsx'), 'utf-8');++ it.each([['src', 'App.tsx'], ['src/l1/l2', '../../App.tsx']])(+ 'scans the project src by default when run from %s',+ async (folder, reported) => {+ const res = await upgrade({from: '0.6.8', apply: true}, {cwd: path.join(dir, folder)});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.sourcePathFound).toBe(true);+ expect(res.data.filesChanged).toBe(1);+ expect(res.data.modifiedFiles).toEqual([reported]);+ expect(appSource()).toContain('emptySearchText="None"');+ },+ SLOW,+ );++ it('reads a path you name relative to the folder you ran in', async () => {+ const res = await upgrade({from: '0.6.8', path: '../..', apply: true}, {cwd: path.join(dir, 'src', 'l1', 'l2')});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.filesChanged).toBe(1);+ expect(appSource()).toContain('emptySearchText="None"');+ }, SLOW);++ it('still rejects a path outside the project', async () => {+ await expect(+ upgrade({from: '0.6.8', path: '../../..'}, {cwd: path.join(dir, 'src', 'l1')}),+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ expect(appSource()).toBe(OLD_PROP_SOURCE);+ }, SLOW);++ it("refreshes the agent docs at the project root, not the folder it ran in", async () => {+ fs.writeFileSync(+ path.join(dir, 'AGENTS.md'),+ `# Agents\n\n${generateCompressedIndex('0.6.8')}\n`,+ );++ const res = await upgrade({from: '0.6.8', apply: true}, {cwd: path.join(dir, 'src', 'l1')});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.agentDocs.action).toBe('refreshed');+ expect(res.data.agentDocs.files).toEqual(['../../AGENTS.md']);+ expect(fs.existsSync(path.join(dir, 'src', 'l1', 'AGENTS.md'))).toBe(false);+ }, SLOW);+});++describe('upgrade.run — the result names files relative to the folder it ran in', () => {+ let dir;+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-receipt-'));+ seedOldPropProject(dir);+ fs.writeFileSync(path.join(dir, 'src', 'Generated.tsx'), `// @generated\n${OLD_PROP_SOURCE}`);+ fs.writeFileSync(path.join(dir, 'src', 'Vendored.tsx'), OLD_PROP_SOURCE);+ fs.writeFileSync(path.join(dir, '.gitattributes'), 'src/Vendored.tsx linguist-generated\n');+ fs.writeFileSync(path.join(dir, 'AGENTS.md'), `# Agents\n\n${generateCompressedIndex('0.6.8')}\n`);+ fs.mkdirSync(path.join(dir, 'frontend'), {recursive: true});+ });+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++ it.each([+ ['frontend', '../'],+ ['.', ''],+ ])('from %s, every file path resolves from that folder', async (folder, up) => {+ const cwd = path.join(dir, folder);++ const res = await upgrade({from: '0.6.8'}, {cwd});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.modifiedFiles).toEqual([`${up}src/App.tsx`]);+ expect(res.data.protectedFiles.map(item => item.file)).toEqual([+ `${up}src/Generated.tsx`,+ `${up}src/Vendored.tsx`,+ ]);+ for (const file of [...res.data.modifiedFiles, ...res.data.protectedFiles.map(item => item.file)]) {+ expect(fs.existsSync(path.join(cwd, file))).toBe(true);+ }+ // The file a declaration names resolves from that folder too.+ const vendored = res.data.protectedFiles.find(item => item.file.endsWith('Vendored.tsx'));+ expect(vendored?.declarations).toEqual([`linguist-generated in ${up}.gitattributes:1`]);+ expect(fs.existsSync(path.join(cwd, `${up}.gitattributes`))).toBe(true);+ }, SLOW);++ it('leaves a result from a run at the project root as it is', () => {+ const result = {type: 'upgrade.run', data: {modifiedFiles: ['src/App.tsx']}};++ expect(relativeToOrigin(result, {cwd: dir})).toBe(result);+ });++ it('rewrites every project-relative path and passes the copied-composition summary through', () => {+ const registryCompositions = {items: [{item: 'example', path: 'components/Example.tsx', files: []}]};+ const result = relativeToOrigin(+ {+ type: 'upgrade.run',+ data: {+ agentDocs: {status: 'stale', files: ['AGENTS.md']},+ modifiedFiles: ['src/App.tsx'],+ protectedFiles: [+ {+ file: 'src/Generated.tsx',+ codemods: ['a'],+ declarations: [+ '@generated marker',+ 'excluded by .gitignore',+ 'excluded by src/.hgignore:3',+ 'linguist-generated in .gitattributes:1',+ 'symbolic link at src/linked',+ 'installed dependency metadata node_modules/x',+ ],+ },+ ],+ declinedCandidates: [{file: 'src/Loose.tsx', reason: 'unproven'}],+ errors: [{file: '.', codemod: 'post-codemod-hook', error: 'failed'}],+ registryCompositions,+ },+ },+ {cwd: dir, origin: path.join(dir, 'apps', 'web')},+ );++ expect(result.data).toEqual({+ agentDocs: {status: 'stale', files: ['../../AGENTS.md']},+ modifiedFiles: ['../../src/App.tsx'],+ protectedFiles: [+ {+ file: '../../src/Generated.tsx',+ codemods: ['a'],+ declarations: [+ '@generated marker',+ 'excluded by ../../.gitignore',+ 'excluded by ../../src/.hgignore:3',+ 'linguist-generated in ../../.gitattributes:1',+ 'symbolic link at ../../src/linked',+ 'installed dependency metadata node_modules/x',+ ],+ },+ ],+ declinedCandidates: [{file: '../../src/Loose.tsx', reason: 'unproven'}],+ errors: [{file: '../..', codemod: 'post-codemod-hook', error: 'failed'}],+ registryCompositions,+ });+ });+});++describe("upgrade.run — the target Core is the project's own", () => {+ let dir;+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-own-core-'));+ seedOldPropProject(dir);+ });+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++ /**+ * A project nested in `dir`, with src/App.tsx using the renamed prop.+ * @param {Record<string, string>} dependencies+ */+ function nestedProject(dependencies) {+ const nested = path.join(dir, 'apps', 'web');+ fs.mkdirSync(path.join(nested, 'src'), {recursive: true});+ fs.writeFileSync(path.join(nested, 'package.json'), JSON.stringify({name: 'web', dependencies}));+ fs.writeFileSync(path.join(nested, 'src', 'App.tsx'), OLD_PROP_SOURCE);+ return nested;+ }++ it.each([+ ['declares no Astryx package', {}],+ ['declares a Core it has not installed', {'@astryxdesign/core': '0.6.8'}],+ ])(+ 'does not upgrade a project that %s to the Core of the home folder above it',+ async (_label, dependencies) => {+ const nested = nestedProject(dependencies);++ await withHome(dir, () =>+ expect(+ upgrade({from: '0.6.8', apply: true}, {cwd: nested}),+ ).rejects.toMatchObject({code: 'ERR_VERSION_DETECT'}),+ );+ expect(fs.readFileSync(path.join(nested, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ expect(fs.readFileSync(path.join(dir, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ },+ SLOW,+ );++ it('names the folder it searched before stopping on a missing Core, from a subfolder (AST-040 FR12)', async () => {+ fs.rmSync(path.join(dir, 'node_modules'), {recursive: true, force: true});+ const sub = path.join(dir, 'src', 'l1');+ const log = vi.spyOn(logger, 'log');+ try {+ await expect(upgrade({from: '0.6.8'}, {cwd: sub})).rejects.toMatchObject({+ code: 'ERR_VERSION_DETECT',+ });+ const lines = log.mock.calls.map(([line]) => String(line));+ expect(lines).toContain('Project root: ../..');+ expect(lines.indexOf('Project root: ../..')).toBeLessThan(+ lines.indexOf('Aborted\n'),+ );+ } finally {+ log.mockRestore();+ }+ }, SLOW);++ it('does not upgrade a nested project that declares a Core it has not installed to the Core above it', async () => {+ const nested = nestedProject({'@astryxdesign/core': '0.6.8'});++ await expect(+ upgrade({from: '0.6.8', apply: true}, {cwd: nested}),+ ).rejects.toMatchObject({code: 'ERR_VERSION_DETECT'});+ expect(fs.readFileSync(path.join(nested, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ }, SLOW);++ it.each([+ ['an override at the workspace root forces', {overrides: {'@astryxdesign/core': '0.7.0'}}, {'@astryxdesign/core': '~0.6.8'}],+ ['a resolution at the workspace root forces', {resolutions: {'@astryxdesign/core': '0.7.0'}}, {'@astryxdesign/core': '0.6.8'}],+ ['only a stale peer range names', {}, null],+ ['the member declares another version of, not yet installed', {}, {'@astryxdesign/core': '0.9.0'}],+ ])(+ 'upgrades a workspace member to a hoisted Core that %s',+ async (_label, rootFields, dependencies) => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'root', private: true, workspaces: ['apps/*'], ...rootFields}),+ );+ const member = dependencies+ ? nestedProject(dependencies)+ : nestedProject({});+ if (!dependencies) {+ fs.writeFileSync(+ path.join(member, 'package.json'),+ JSON.stringify({name: 'web', peerDependencies: {'@astryxdesign/core': '^0.6.8'}}),+ );+ }++ const res = await upgrade({from: '0.6.8', apply: true}, {cwd: member});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.to).toBe('0.7.0');+ expect(res.data.modifiedFiles).toEqual(['src/App.tsx']);+ expect(fs.readFileSync(path.join(member, 'src', 'App.tsx'), 'utf-8')).toContain('emptySearchText="None"');+ },+ SLOW,+ );++ it('does not upgrade a project its workspace does not list to the hoisted Core', async () => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'root', private: true, workspaces: ['packages/*']}),+ );+ const project = nestedProject({'@astryxdesign/core': '0.9.0'});++ await expect(+ upgrade({from: '0.6.8', apply: true}, {cwd: project}),+ ).rejects.toMatchObject({code: 'ERR_VERSION_DETECT'});+ expect(fs.readFileSync(path.join(project, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ }, SLOW);++ it.each([[['apps/*']], [['{apps/*,tools/*}']]])('upgrades a member that declares no Astryx package, in its own src, when the workspace lists %j', async workspaces => {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'root', private: true, workspaces, dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const member = nestedProject({});++ const res = await upgrade({from: '0.6.8', apply: true}, {cwd: path.join(member, 'src')});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.modifiedFiles).toEqual(['App.tsx']);+ expect(fs.readFileSync(path.join(member, 'src', 'App.tsx'), 'utf-8')).toContain('emptySearchText="None"');+ expect(fs.readFileSync(path.join(dir, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ }, SLOW);+});++describe('upgrade.run — the project is the nearest folder that declares Astryx', () => {+ let home;+ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-home-'));+ });+ afterEach(() => fs.rmSync(home, {recursive: true, force: true}));++ // Astryx installed in a home folder whose src holds loose files and another+ // project, run from a folder with no package.json.+ it('does not upgrade the home folder from a folder inside it', async () => {+ seedOldPropProject(home);+ fs.mkdirSync(path.join(home, 'src', 'repoA', 'src'), {recursive: true});+ fs.writeFileSync(+ path.join(home, 'src', 'repoA', 'package.json'),+ JSON.stringify({name: 'repoA', dependencies: {'@astryxdesign/core': '0.6.8'}}),+ );+ fs.writeFileSync(path.join(home, 'src', 'repoA', 'src', 'a.tsx'), OLD_PROP_SOURCE);+ const desktop = path.join(home, 'Desktop');+ fs.mkdirSync(desktop, {recursive: true});++ await withHome(home, () =>+ expect(+ upgrade({from: '0.6.8', apply: true}, {cwd: desktop}),+ ).rejects.toMatchObject({code: 'ERR_VERSION_DETECT'}),+ );+ expect(fs.readFileSync(path.join(home, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ expect(fs.readFileSync(path.join(home, 'src', 'repoA', 'src', 'a.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ }, SLOW);++ // Installing Core does not make a folder a project.+ it('treats a folder that installs Core without declaring it as part of the project above it', async () => {+ seedOldPropProject(home);+ const tool = path.join(home, 'tools', 'codegen');+ const core = path.join(tool, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(path.join(tool, 'package.json'), JSON.stringify({name: 'codegen'}));+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({name: '@astryxdesign/core', version: '0.9.0'}));++ const res = await upgrade({from: '0.6.8', apply: true}, {cwd: tool});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.to).toBe('0.7.0');+ expect(res.data.modifiedFiles).toEqual(['../../src/App.tsx']);+ }, SLOW);++ it('names the project root and the folder it scans before a dry run in a folder that installs Core without declaring it', async () => {+ seedOldPropProject(home);+ const tool = path.join(home, 'tools', 'codegen');+ const core = path.join(tool, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(path.join(tool, 'package.json'), JSON.stringify({name: 'codegen'}));+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({name: '@astryxdesign/core', version: '0.9.0'}));+ const log = vi.spyOn(logger, 'log');+ try {+ const res = await upgrade({from: '0.6.8'}, {cwd: tool});++ expect(res.type).toBe('upgrade.run');+ const lines = log.mock.calls.map(([line]) => String(line));+ expect(lines).toContain('Project root: ../..');+ expect(lines).toContain(`Source folder: ${path.join('..', '..', 'src')}`);+ expect(fs.readFileSync(path.join(home, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ } finally {+ log.mockRestore();+ }+ }, SLOW);++ it('upgrades the home folder as a folder outside any project, when run there', async () => {+ seedOldPropProject(home);++ const res = await withHome(home, () => upgrade({from: '0.6.8', apply: true}, {cwd: home}));++ expect(res.type).toBe('upgrade.run');+ expect(res.data.modifiedFiles).toEqual(['src/App.tsx']);+ expect(fs.readFileSync(path.join(home, 'src', 'App.tsx'), 'utf-8')).toContain('emptySearchText="None"');+ }, SLOW);++ it('does not leave a repository for the project around it', async () => {+ seedOldPropProject(home);+ const repo = path.join(home, 'vendor', 'repo');+ fs.mkdirSync(path.join(repo, '.git'), {recursive: true});+ fs.mkdirSync(path.join(repo, 'src'), {recursive: true});+ fs.writeFileSync(path.join(repo, 'package.json'), JSON.stringify({name: 'repo'}));+ fs.writeFileSync(path.join(repo, 'src', 'App.tsx'), OLD_PROP_SOURCE);++ await expect(+ upgrade({from: '0.6.8', apply: true}, {cwd: repo}),+ ).rejects.toMatchObject({code: 'ERR_VERSION_DETECT'});+ expect(fs.readFileSync(path.join(repo, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ expect(fs.readFileSync(path.join(home, 'src', 'App.tsx'), 'utf-8')).toBe(OLD_PROP_SOURCE);+ }, SLOW);+});diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjsindex a073f26f35..279a5f1ef1 100644--- a/packages/cli/api/upgrade/upgrade.doc.mjs+++ b/packages/cli/api/upgrade/upgrade.doc.mjs@@ -77,8 +77,9 @@ export const doc = {{name: 'options.path',type: 'string',- description: 'Source directory to scan.',- default: './src',+ description:+ 'Source directory to scan. A path you name, in any spelling, is relative to `ctx.cwd`. When it is omitted, the upgrade scans `./src` at the project root.',+ default: './src at the project root',},{name: 'options.installDeps',@@ -103,7 +104,8 @@ export const doc = {{name: 'ctx.cwd',type: 'string',- description: 'Directory to run the upgrade in.',+ description:+ 'Any folder in the project to upgrade. The upgrade runs at the project root: the nearest folder at or above it whose package.json declares an Astryx package, or that a workspace whose root declares one lists, found without passing a repository root or counting the home folder. With no such folder, it runs in `ctx.cwd`. File paths in the result are relative to `ctx.cwd`, except that a run at the project root names copied-composition paths relative to the scanned source directory.',default: 'process.cwd()',},],@@ -135,10 +137,13 @@ export const doc = {when: '`from` is missing (and neither `list` nor `registry` is set); `list` and `registry` are both set; `list` is combined with `from`, `force`, `apply`, `path` (non-default), `codemod`, `skipCodemod`, `integration` or `installDeps`; `registry` is combined with `from`, `force`, `codemod`, `skipCodemod`, `integration` or `installDeps`; an `integration` specifier is invalid or not installed; or astryx.config fails to load or validate and no pending config codemod repairs it',},{code: 'ERR_INVALID_VERSION', when: '`from` is not a valid semver string'},- {code: 'ERR_PATH_TRAVERSAL', when: '`path` resolves outside cwd'},+ {+ code: 'ERR_PATH_TRAVERSAL',+ when: '`path` resolves outside the project root',+ },{code: 'ERR_VERSION_DETECT',- when: 'neither @astryxdesign/core nor legacy @xds/core is installed in cwd; with `registry`, only when copied-composition receipts exist and @astryxdesign/core is not installed',+ when: "the project has installed neither @astryxdesign/core nor legacy @xds/core in its own node_modules, nor, for a member its workspace lists, in a folder up to the workspace root (with no Astryx project, in `ctx.cwd`'s own node_modules); with `registry`, only when copied-composition receipts exist and @astryxdesign/core is not installed",},{code: 'ERR_DEP_MISSING',diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjsindex b95f428172..d2101dd603 100644--- a/packages/cli/api/upgrade/upgrade.mjs+++ b/packages/cli/api/upgrade/upgrade.mjs@@ -24,6 +24,7 @@import {list} from './list/list.mjs';import {registryUpgrade} from './registry/registry.mjs';import {run} from './run/run.mjs';+import {relativeToOrigin, scopeToProject} from './_adapter.mjs';import {isValidSemver} from '../../foundation/env/semver.mjs';import {getCliInvocation} from '../../foundation/env/package-manager.mjs';import {isOutsideProject} from '../../foundation/env/project-scope.mjs';@@ -88,7 +89,11 @@ export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {logger.log('Aborted\n');throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);}- return registryUpgrade(options, {cwd});+ const scoped = scopeToProject(options, cwd);+ return registryUpgrade(scoped.options, {+ cwd: scoped.cwd,+ origin: scoped.origin,+ });}if (!options.list && !options.from) {@@ -112,5 +117,11 @@ export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {return list();}- return run(options, {cwd});+ // A run from a subfolder upgrades the project the folder belongs to, and+ // names files relative to the folder it ran in.+ const scoped = scopeToProject(options, cwd);+ return relativeToOrigin(+ await run(scoped.options, {cwd: scoped.cwd, origin: scoped.origin}),+ scoped,+ );}diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjsindex 2ce6e52bf9..f5644bdf51 100644--- a/packages/cli/api/upgrade/upgrade.type.mjs+++ b/packages/cli/api/upgrade/upgrade.type.mjs@@ -45,7 +45,7 @@* @property {'missing' | 'stale' | 'current'} status* @property {string} installedVersion Installed core version the block should reflect.* @property {string[]} fromVersions Distinct stale block versions found (the "from" side of the refresh).- * @property {string[]} files Files rewritten (apply) or that would be rewritten (dry-run).+ * @property {string[]} files Files rewritten (apply) or that would be rewritten (dry-run), relative to the folder the command ran in.* @property {boolean} refreshed True only when a block was actually rewritten (apply mode).* @property {'refreshed' | 'would-refresh' | 'nudge-init' | 'error' | 'none'} action*/@@ -70,7 +70,9 @@*//**- * Aggregate receipt for ShadCN-copied composition reconciliation.+ * Aggregate receipt for ShadCN-copied composition reconciliation. File paths+ * are relative to the scanned source directory, or, when the upgrade ran in a+ * folder below the project root, to that folder.* @typedef {object} RegistryCompositionSummary* @property {boolean} applied* @property {boolean} ok False when conflicts, missing files, invalid receipts, or failures remain.@@ -99,7 +101,7 @@/*** A required codemod change blocked by effective working-tree protection.* @typedef {object} ProtectedCodemodFile- * @property {string} file Project-relative path.+ * @property {string} file Path relative to the folder the command ran in.* @property {string[]} codemods Codemods that still require a change.* @property {string[]} reasons Protection categories (generated, vendored, ignored, and hard boundaries).* @property {string[]} declarations Effective declarations that protect the file.@@ -132,11 +134,11 @@* @property {boolean} [data.complete] False when protected required changes remain.* @property {'ERR_CODEMOD_PROTECTED'} [data.errorCode] Stable incomplete-result code when complete is false.* @property {number} [data.filesChanged] Distinct files changed across core + integration codemods (apply mode). One file that four codemods each changed counts once.- * @property {string[]} [data.modifiedFiles] Project-relative files changed or previewed.+ * @property {string[]} [data.modifiedFiles] Files changed or previewed, relative to the folder the command ran in.* @property {ProtectedCodemodFile[]} [data.protectedFiles] Protected files that still require a codemod change after regeneration.- * @property {Array<{file: string, location?: string, reason: string}>} [data.declinedCandidates] Candidates left unchanged because proof was insufficient.+ * @property {Array<{file: string, location?: string, reason: string}>} [data.declinedCandidates] Candidates left unchanged because proof was insufficient. Each `file` is relative to the folder the command ran in.* @property {number} [data.transformsApplied] Total codemod changes. A code or config codemod counts once for each file it changed, so one file changed by four of them counts four times; a project codemod counts once, however many files it writes.- * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed.+ * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed. Each `file` is relative to the folder the command ran in.* @property {CliBehindCore} [data.cliBehindCore] Present only when the installed Core is newer than this CLI: codemods for the releases after `cliBehindCore.cliVersion` did not run.*/diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjsindex c4c90781e4..1cbf87f4c4 100644--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs@@ -21,6 +21,7 @@ export const doc = {'agent-docs block when Core or configured integration guidance changes. ' +'Dry-run by default. --apply writes codemod and receipt changes, runs hooks, then refreshes agent docs. ' +'Anything a post-codemod hook prints goes to stderr, so stdout carries only the result. ' ++ 'Run from a folder inside a project, it upgrades that project and names files in the result relative to the folder you ran it in. ' +'ShadCN-copied compositions are checked automatically during a normal upgrade, or alone with --registry. ' +'Outside a project, --list lists the codemods this release ships and --registry finds no copied compositions to update; ' +'a migration writes nothing and fails with ERR_VERSION_DETECT, because no installed Core names its target.',@@ -69,8 +70,9 @@ export const doc = {{flag: '--path <dir>',param: 'options.path',- description: 'Source directory to scan',- default: './src',+ description:+ "Source directory to scan, relative to where you run the command, however you spell it. Without --path, the project's src folder, from any folder in the project",+ default: './src at the project root',},{flag: '--install-deps',diff --git a/packages/cli/clients/cli/commands/upgrade.mjs b/packages/cli/clients/cli/commands/upgrade.mjsindex 54d1a15bce..aea6ea4a46 100644--- a/packages/cli/clients/cli/commands/upgrade.mjs+++ b/packages/cli/clients/cli/commands/upgrade.mjs@@ -31,8 +31,9 @@ export function registerUpgrade(program) {action:/*** @param {import('../../../api/upgrade/upgrade.mjs').UpgradeOptions} options+ * @param {import('commander').Command} command*/- async options => {+ async (options, command) => {const json = program.opts().json || false;const isList = Boolean(options.list);// Silence the logger for --list so the handler renders from the@@ -42,8 +43,14 @@ export function registerUpgrade(program) {/** @type {import('../../../api/upgrade/upgrade.type.mjs').UpgradeListResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeRegistryResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeStatusResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeRunResponse} */let result;+ // `--path` shows its default in help, but a path nobody typed is the+ // project's src, not one read from this folder: leave it unset.+ const apiOptions =+ command.getOptionValueSource('path') === 'default'+ ? {...options, path: undefined}+ : options;try {- result = await upgradeApi(options, {cwd: process.cwd()});+ result = await upgradeApi(apiOptions, {cwd: process.cwd()});} catch (e) {// Re-enable the logger so the error is visible in text mode.// For --list the logger was silent; for other modes the APIdiff --git a/packages/cli/clients/cli/commands/upgrade.subfolder-path.test.mjs b/packages/cli/clients/cli/commands/upgrade.subfolder-path.test.mjsnew file mode 100644index 0000000000..56de20c38a--- /dev/null+++ b/packages/cli/clients/cli/commands/upgrade.subfolder-path.test.mjs@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx upgrade` from a folder inside a project: a `--path` you type+ * is read from that folder, however you spell it, and without `--path` the+ * upgrade scans the project's own src. The option's default must not read as+ * a typed `./src`. The `--json` result names files relative to the folder the+ * command ran in.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {runCli} from '../../../test-utils/run-cli.mjs';++/** Core 0.7.0 renamed this prop; its codemod renames it on Typeahead. */+const OLD_PROP_SOURCE =+ "import {Typeahead} from '@astryxdesign/core';\n" ++ 'export const App = () => <Typeahead label="Fruit" emptySearchResultsText="None" />;\n';++let root;++/** @param {string} rel @param {string} body */+function write(rel, body) {+ const file = path.join(root, rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, body);+}++/** @param {string} rel */+const renamed = rel =>+ fs+ .readFileSync(path.join(root, rel), 'utf-8')+ .includes('emptySearchText="None"');++beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-upgrade-subfolder-'));+ write(+ 'package.json',+ JSON.stringify({+ name: 'app',+ private: true,+ dependencies: {'@astryxdesign/core': '0.7.0'},+ }),+ );+ write(+ 'node_modules/@astryxdesign/core/package.json',+ JSON.stringify({name: '@astryxdesign/core', version: '0.7.0'}),+ );+ write('src/App.tsx', OLD_PROP_SOURCE);+ // A folder inside the project with source of its own and no package.json.+ write('frontend/src/App.tsx', OLD_PROP_SOURCE);+});++afterEach(() => {+ fs.rmSync(root, {recursive: true, force: true});+});++/** @param {string[]} args @param {string} [folder] */+async function upgradeFrom(args, folder = 'frontend') {+ const r = await runCli(+ ['upgrade', '--from', '0.6.8', ...args, '--apply', '--json'],+ {+ cwd: path.join(root, folder),+ },+ );+ expect(r.status).toBe(0);+ return JSON.parse(r.stdout);+}++describe('upgrade --path from a folder inside the project', () => {+ it.each([['./src'], ['src'], ['src/'], ['./src/']])(+ 'reads --path %s from the folder you ran in',+ async spelling => {+ const result = await upgradeFrom(['--path', spelling]);++ expect(result.data.modifiedFiles).toEqual(['src/App.tsx']);+ expect(renamed('frontend/src/App.tsx')).toBe(true);+ expect(renamed('src/App.tsx')).toBe(false);+ },+ );++ it("scans the project's src without --path", async () => {+ const result = await upgradeFrom([]);++ expect(result.data.modifiedFiles).toEqual(['../src/App.tsx']);+ expect(renamed('src/App.tsx')).toBe(true);+ expect(renamed('frontend/src/App.tsx')).toBe(false);+ });++ it('names files from the project root when run there', async () => {+ const result = await upgradeFrom([], '.');++ expect(result.data.modifiedFiles).toEqual(['src/App.tsx']);+ });+});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 7aa69b4331..5c49ffde61 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -40,7 +40,7 @@ import {parseConfig} from '../../authoring/config/parse.mjs';import {loadIntegrations,loadLocalIntegration,- resolvePackageDir,+ resolveInstalledIntegrationDir,} from '../integrations/integrations.mjs';import {loadAutolinkCandidates} from '../integrations/autolink.mjs';import {@@ -65,7 +65,7 @@ import {discoverValidIntegrationComponents,} from '../discovery/component-discovery.mjs';import {resolveComponentReplacements} from '../discovery/component-replacement.mjs';-import {CLI_ROOT, findCoreDir, findProjectCoreDir} from '../fs/paths.mjs';+import {CLI_ROOT, findCoreDir, findPackageRoot, findProjectCoreDir} from '../fs/paths.mjs';import {applyTemplateReplacements,effectiveTemplateDiscovery,@@ -223,7 +223,7 @@ async function loadConfiguredIntegrations(specs, {cwd, fresh}) {/** @type {string|undefined} */let packageDir;try {- packageDir = resolvePackageDir(spec, cwd);+ packageDir = resolveInstalledIntegrationDir(spec, cwd);} catch {// Not a bare package name: there is no install location to record.}@@ -326,22 +326,6 @@ export const CONFIG_BASENAMES = [export const DEFAULT_ISSUES_URL ='https://github.com/facebook/astryx/issues/new';-/**- * Find the directory of the nearest package.json walking up from startDir.- * @param {string} startDir- * @returns {string|null}- */-function findPackageRoot(startDir) {- let dir = startDir;- for (let i = 0; i < 50; i++) {- if (fs.existsSync(path.join(dir, 'package.json'))) return dir;- const parent = path.dirname(dir);- if (parent === dir) break;- dir = parent;- }- return null;-}-/*** Whether this project accepts `debug` handlers contributed by the* integrations it loads.@@ -506,7 +490,8 @@ export class Project {// The project root: the config's directory when there is one (findConfigPath// resolves the config as a sibling of the nearest package.json, so the two// agree), otherwise that package.json's directory. Dependencies are declared- // there, and node_modules sits there.+ // there, and installed packages resolve from there up the node_modules+ // chain.const projectDir = configPath? path.dirname(configPath): (findPackageRoot(cwd) ?? cwd);diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex 227a7ec4b0..907473a701 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -856,6 +856,36 @@ describe('Project loads each integration in isolation', () => {});});+describe('Project finds configured integrations a workspace hoists', () => {+ // npm, Yarn and Bun workspaces install a member's dependencies at the+ // workspace root, so the member's own node_modules does not hold them.+ it('loads an integration named in a member config from the workspace root', async () => {+ scaffold();+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'root', private: true, workspaces: ['apps/*']}),+ );+ fs.rmSync(path.join(tmpDir, 'astryx.config.mjs'));+ const member = path.join(tmpDir, 'apps', 'web');+ fs.mkdirSync(member, {recursive: true});+ fs.writeFileSync(path.join(member, 'package.json'), JSON.stringify({name: 'web'}));+ fs.writeFileSync(+ path.join(member, 'astryx.config.mjs'),+ `export default ${JSON.stringify({integrations: ['@acme/widgets']})};\n`,+ );++ const project = await Project.load(member);++ const widgets = (await project.components()).filter(+ component => component.package === '@acme/widgets',+ );+ expect(widgets.map(component => component.name)).toEqual(['Widget']);+ expect(await project.issues()).not.toContainEqual(+ expect.objectContaining({package: '@acme/widgets', code: 'integration_error'}),+ );+ });+});+describe('Project.issuesUrl routing', () => {it('routes core to config.issuesUrl, falling back to the default', async () => {scaffold({issuesUrl: 'https://example.com/core'});diff --git a/packages/cli/foundation/discovery/template-needs.mjs b/packages/cli/foundation/discovery/template-needs.mjsindex 43944e43f2..883077487a 100644--- a/packages/cli/foundation/discovery/template-needs.mjs+++ b/packages/cli/foundation/discovery/template-needs.mjs@@ -18,7 +18,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import module from 'node:module';-import {CLI_ROOT} from '../fs/paths.mjs';+import {CLI_ROOT, findWorkspaceRoot} from '../fs/paths.mjs';import {detectStylingSystem} from '../agent-docs/agent-docs.mjs';import {decidePackageManagerIn,@@ -71,49 +71,6 @@ const ADD_VERB = {npm: 'npm install',};-/**- * Whether a package.json declares a workspace (`workspaces` field).- * @param {string} dir- * @returns {{exists: boolean, declaresWorkspace: boolean}}- */-function readPackageJson(dir) {- const pkgPath = path.join(dir, 'package.json');- if (!fs.existsSync(pkgPath)) return {exists: false, declaresWorkspace: false};- try {- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));- return {exists: true, declaresWorkspace: pkg.workspaces != null};- } catch {- return {exists: true, declaresWorkspace: false};- }-}--/**- * The workspace root (AST-048 FR15): the nearest directory at or above the- * target that declares a workspace, by `pnpm-workspace.yaml` or a package.json- * `workspaces` field; outside a workspace, the nearest package.json's- * directory; with no package.json, the target itself.- * @param {string} target- * @returns {string}- */-function findWorkspaceRoot(target) {- let dir = path.resolve(target);- /** @type {string | null} */- let nearestPackage = null;- for (;;) {- const pkg = readPackageJson(dir);- if (- fs.existsSync(path.join(dir, 'pnpm-workspace.yaml')) ||- pkg.declaresWorkspace- ) {- return dir;- }- if (pkg.exists && nearestPackage == null) nearestPackage = dir;- const parent = path.dirname(dir);- if (parent === dir) return nearestPackage ?? path.resolve(target);- dir = parent;- }-}-/*** The project's package manager for an install command (AST-048 FR17, FR19):* the nearest directory from the target up to the workspace root that has adiff --git a/packages/cli/foundation/fs/paths.mjs b/packages/cli/foundation/fs/paths.mjsindex fbd6b3ef3f..14ca5a4fc8 100644--- a/packages/cli/foundation/fs/paths.mjs+++ b/packages/cli/foundation/fs/paths.mjs@@ -3,11 +3,14 @@/*** @file Path resolution utilities for Astryx CLI*- * Finds packages/core, project root, and CLI package root.+ * Finds the Astryx project a folder belongs to and its workspace root, the+ * project's @astryxdesign/core and the other packages it installed, and the+ * CLI package root.*/import * as fs from 'node:fs';import {createRequire} from 'node:module';+import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {listDir, pathExists} from './listing-cache.mjs';@@ -21,6 +24,9 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));/** Root of the @astryxdesign/cli package */export const CLI_ROOT = path.resolve(__dirname, '..', '..');+/** The package every Core lookup answers for. */+const CORE_PACKAGE = '@astryxdesign/core';+/*** The Core a command answers from: the project's (see* {@link findProjectCoreDir}), else, when a copy other than the project's own@@ -148,12 +154,10 @@ function carriedCoreFor(startDir, fetch = false) {}/**- * Find packages/core directory by walking up from startDir.- * Also checks node_modules/@astryxdesign/core for installed usage.- *- * The project's Core only: in the folder or four above it, the reach every- * released version used, else from the folder of the package.json that makes- * the folder part of a project, however deep the folder is.+ * The project's own @astryxdesign/core, never a carried one: found from the+ * folder (see {@link findNearbyCoreDir}), else from the folder of the+ * package.json that makes the folder part of a project, however deep the+ * folder is.** @param {string} [startDir]* @returns {string | null}@@ -171,38 +175,464 @@ export function findProjectCoreDir(startDir = process.cwd()) {}/**- * The Core installed in `startDir` or one of the four folders above it.+ * How many folders, counting the start, the read lookups always search: the+ * reach they had in released versions, so nothing they found before goes+ * missing. Past this reach they continue only up to the workspace root of the+ * Astryx project the start folder belongs to.+ */+const CORE_REACH = 5;+const INSTALLED_REACH = 6;++/** Package scopes whose declaration makes a package.json an Astryx project. */+const ASTRYX_SCOPES = ['@astryxdesign/', '@xds/'];++/** package.json fields in which a package declares what it depends on. */+const DEPENDENCY_FIELDS = [+ 'dependencies',+ 'devDependencies',+ 'optionalDependencies',+ 'peerDependencies',+];++/** Folders that mark a repository root; the project search stops there. */+const REPOSITORY_MARKERS = ['.git', '.hg', '.sl'];++/**+ * `startDir` and every folder above it, nearest first, up to the filesystem+ * root: the folders Node's resolver searches for `node_modules`.+ ** @param {string} startDir- * @returns {string | null}+ * @returns {Generator<string>}*/-function findNearbyCoreDir(startDir) {- let dir = startDir;+function* foldersUpFrom(startDir) {+ let dir = path.resolve(startDir);+ for (;;) {+ yield dir;+ const parent = path.dirname(dir);+ if (parent === dir) return;+ dir = parent;+ }+}- for (let i = 0; i < 5; i++) {- const candidate = path.join(dir, 'packages', 'core');- if (fs.existsSync(candidate)) {- return candidate;+/**+ * `dir/node_modules/<name>` when the package is installed there. Its+ * package.json decides, so a stale empty folder is not an install.+ *+ * @param {string} dir+ * @param {string} name+ * @returns {string|null}+ */+function installedIn(dir, name) {+ const candidate = path.join(dir, 'node_modules', ...name.split('/'));+ return fs.existsSync(path.join(candidate, 'package.json')) ? candidate : null;+}++/**+ * The package.json in `dir`, or null when it is missing or not a JSON object.+ *+ * @param {string} dir+ * @returns {Record<string, any>|null}+ */+function readPackageJson(dir) {+ try {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'),+ );+ return pkg && typeof pkg === 'object' ? pkg : null;+ } catch {+ return null;+ }+}++/**+ * Whether `dir` is @astryxdesign/core's own source, by the name in its+ * package.json. The folder name says nothing: many monorepos keep an unrelated+ * package in `packages/core`.+ *+ * @param {string} dir+ * @returns {boolean}+ */+function isCoreSource(dir) {+ return readPackageJson(dir)?.name === CORE_PACKAGE;+}++/**+ * `p` resolved through symlinks when it exists, so folders compare equal+ * however they were reached.+ *+ * @param {string} p+ * @returns {string}+ */+function realDir(p) {+ try {+ return fs.realpathSync(path.resolve(p));+ } catch {+ return path.resolve(p);+ }+}++/**+ * The home folder, resolved through symlinks, or null when there is none.+ *+ * @returns {string|null}+ */+function homeFolder() {+ try {+ const home = os.homedir();+ return home ? realDir(home) : null;+ } catch {+ return null;+ }+}++/**+ * Whether `child` lies strictly inside `parent`.+ *+ * @param {string} child+ * @param {string} parent+ * @returns {boolean}+ */+function isInside(child, parent) {+ const rel = path.relative(parent, child);+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);+}++/**+ * Whether the package.json in `dir` declares an Astryx package, in any+ * dependency field.+ *+ * @param {string} dir+ * @returns {boolean}+ */+function declaresAstryx(dir) {+ const pkg = readPackageJson(dir);+ if (pkg == null) return false;+ return DEPENDENCY_FIELDS.some(field => {+ const deps = pkg[field];+ return (+ deps != null &&+ typeof deps === 'object' &&+ Object.keys(deps).some(name =>+ ASTRYX_SCOPES.some(scope => name.startsWith(scope)),+ )+ );+ });+}++/**+ * The project root: the directory of the nearest package.json at or above+ * `startDir`, or null when there is none.+ *+ * @param {string} startDir+ * @returns {string|null}+ */+export function findPackageRoot(startDir) {+ for (const dir of foldersUpFrom(startDir)) {+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;+ }+ return null;+}++/**+ * The Astryx project `startDir` belongs to: the nearest folder at or above it+ * whose package.json declares an Astryx package (`@astryxdesign/*`, or the+ * legacy `@xds/*`), or that a workspace whose root declares one lists as a+ * member. The search stops at a repository root, and it ends at the home+ * folder without counting it. Returns null when no folder qualifies.+ *+ * @param {string} startDir+ * @returns {string|null}+ */+export function findAstryxProject(startDir) {+ const start = path.resolve(startDir);+ const home = homeFolder();+ for (const dir of foldersUpFrom(start)) {+ if (home != null && realDir(dir) === home) return null;+ if (declaresAstryx(dir) || isAstryxWorkspaceMember(dir)) return dir;+ if (+ REPOSITORY_MARKERS.some(marker => fs.existsSync(path.join(dir, marker)))+ ) {+ return null;}+ }+ return null;+}- const nodeModules = path.join(dir, 'node_modules', '@astryxdesign', 'core');- if (fs.existsSync(nodeModules)) {- return nodeModules;+/**+ * The workspace root (`spec:AST-048` FR15): the nearest directory at or above+ * `startDir` that declares a workspace, by a `pnpm-workspace.yaml` or a+ * package.json `workspaces` field; outside a workspace, the directory of the+ * nearest package.json; with no package.json, `startDir` itself.+ *+ * @param {string} startDir+ * @returns {string}+ */+export function findWorkspaceRoot(startDir) {+ /** @type {string|null} */+ let nearestPackage = null;+ for (const dir of foldersUpFrom(startDir)) {+ if (+ fs.existsSync(path.join(dir, 'pnpm-workspace.yaml')) ||+ readPackageJson(dir)?.workspaces != null+ ) {+ return dir;}+ if (+ nearestPackage == null &&+ fs.existsSync(path.join(dir, 'package.json'))+ ) {+ nearestPackage = dir;+ }+ }+ return nearestPackage ?? path.resolve(startDir);+}- const parent = path.dirname(dir);- if (parent === dir) break;- dir = parent;+/**+ * The highest folder a lookup for `project`'s packages searches: its+ * workspace root, where a workspace keeps the packages its members share. For+ * a project inside the home folder, never the home folder or above.+ *+ * @param {string} project+ * @returns {string}+ */+function workspaceBound(project) {+ const workspace = findWorkspaceRoot(project);+ const home = homeFolder();+ if (+ home != null &&+ isInside(realDir(project), home) &&+ !isInside(realDir(workspace), home)+ ) {+ return project;}+ return workspace;+}++/**+ * Escape `text` for use inside a regular expression.+ * @param {string} text+ * @returns {string}+ */+function escapeRegExp(text) {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}+/**+ * The alternatives of the brace list that opens at `glob[start]`, split at+ * its own commas, and the index of its closing brace; null when it is never+ * closed.+ *+ * @param {string} glob+ * @param {number} start+ * @returns {{alternatives: string[], end: number} | null}+ */+function braceList(glob, start) {+ const alternatives = [];+ let depth = 0;+ let from = start + 1;+ for (let i = start; i < glob.length; i++) {+ if (glob[i] === '{') {+ depth++;+ } else if (glob[i] === '}' && --depth === 0) {+ alternatives.push(glob.slice(from, i));+ return {alternatives, end: i};+ } else if (glob[i] === ',' && depth === 1) {+ alternatives.push(glob.slice(from, i));+ from = i + 1;+ }+ }return null;}+/**+ * The regular-expression source for a workspace glob: `*` and `?` stay+ * within one folder name, `**` spans any number of folders, and `{a,b}`+ * matches either alternative, each a glob of its own.+ *+ * @param {string} glob+ * @returns {string}+ */+function globSource(glob) {+ let source = '';+ for (let i = 0; i < glob.length; i++) {+ const char = glob[i];+ const list = char === '{' ? braceList(glob, i) : null;+ if (char === '*' && glob[i + 1] === '*') {+ // `**/` also matches no folder at all.+ source += glob[i + 2] === '/' ? '(?:.*/)?' : '.*';+ i += glob[i + 2] === '/' ? 2 : 1;+ } else if (char === '*') {+ source += '[^/]*';+ } else if (char === '?') {+ source += '[^/]';+ } else if (list) {+ source += `(?:${list.alternatives.map(globSource).join('|')})`;+ i = list.end;+ } else {+ source += escapeRegExp(char);+ }+ }+ return source;+}++/**+ * A regular expression for a workspace pattern, tested against a member's+ * path relative to the workspace root (see `globSource`).+ *+ * @param {string} pattern+ * @returns {RegExp}+ */+function workspacePatternRegExp(pattern) {+ const glob = pattern+ .trim()+ .replace(/^(?:\.\/)+/, '')+ .replace(/\/+$/, '');+ return new RegExp(`^${globSource(glob)}$`);+}++/**+ * The `packages` list in the pnpm-workspace.yaml in `dir`, as block or flow+ * YAML; empty when there is none.+ *+ * @param {string} dir+ * @returns {string[]}+ */+function pnpmWorkspacePatterns(dir) {+ let text;+ try {+ text = fs.readFileSync(path.join(dir, 'pnpm-workspace.yaml'), 'utf-8');+ } catch {+ return [];+ }+ const lines = text.split(/\r?\n/);+ const start = lines.findIndex(line => /^packages\s*:/.test(line));+ if (start === -1) return [];+ /** @param {string} item */+ const unquote = item => item.trim().replace(/^(['"])(.*)\1$/, '$2');+ const inline = lines[start]+ .replace(/^packages\s*:/, '')+ .replace(/\s#.*$/, '')+ .trim();+ if (inline.startsWith('[')) {+ return inline+ .replace(/^\[|\]$/g, '')+ .split(',')+ .map(unquote)+ .filter(Boolean);+ }+ /** @type {string[]} */+ const patterns = [];+ for (const line of lines.slice(start + 1)) {+ if (line.trim() === '' || line.trim().startsWith('#')) continue;+ const item = /^\s*-\s*(.+?)\s*(?:\s#.*)?$/.exec(line);+ if (!item) break;+ patterns.push(unquote(item[1]));+ }+ return patterns;+}++/**+ * Whether the workspace rooted at `root` lists `dir` as a member: a pattern+ * in its package.json `workspaces` (an array, or `{packages: [...]}`) or its+ * pnpm-workspace.yaml `packages` matches `dir`, and no `!` pattern excludes+ * it.+ *+ * @param {string} dir+ * @param {string} root+ * @returns {boolean}+ */+function isWorkspaceMember(dir, root) {+ const rel = path.relative(root, dir).split(path.sep).join('/');+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return false;+ const workspaces = readPackageJson(root)?.workspaces;+ const patterns = [+ ...(Array.isArray(workspaces) ? workspaces : (workspaces?.packages ?? [])),+ ...pnpmWorkspacePatterns(root),+ ].filter(pattern => typeof pattern === 'string');+ const matches = (/** @type {string} */ pattern) =>+ workspacePatternRegExp(pattern).test(rel);+ return (+ patterns.some(pattern => !pattern.startsWith('!') && matches(pattern)) &&+ !patterns.some(+ pattern => pattern.startsWith('!') && matches(pattern.slice(1)),+ )+ );+}++/**+ * Whether `dir` is a member its workspace lists, where the workspace root+ * declares an Astryx package. Such a member uses the Astryx its workspace+ * installs, so it is an Astryx project of its own.+ *+ * @param {string} dir+ * @returns {boolean}+ */+function isAstryxWorkspaceMember(dir) {+ if (!fs.existsSync(path.join(dir, 'package.json'))) return false;+ const root = workspaceBound(dir);+ return root !== dir && declaresAstryx(root) && isWorkspaceMember(dir, root);+}++/**+ * The folders a read lookup searches, nearest first: `startDir` and the+ * `reach - 1` folders above it, as released versions did; then the root of+ * the Astryx project `startDir` belongs to, if any, and the folders from it up+ * to its workspace root. Past the reach the search starts at the project root,+ * so a folder between the two that installs packages but declares no Astryx+ * package (a tool inside the project) never answers for the project.+ *+ * @param {string} startDir+ * @param {number} reach+ * @returns {Generator<string>}+ */+function* readFolders(startDir, reach) {+ /** @type {Set<string>} */+ const searched = new Set();+ for (const dir of foldersUpFrom(startDir)) {+ if (searched.size >= reach) break;+ searched.add(dir);+ yield dir;+ }+ const project = findAstryxProject(startDir);+ if (project == null) return;+ const bound = workspaceBound(project);+ for (const dir of foldersUpFrom(project)) {+ if (!searched.has(dir)) yield dir;+ if (dir === bound) return;+ }+}++/**+ * The @astryxdesign/core installed for `startDir`.+ *+ * Searches `startDir` and the four folders above it, as released versions+ * did, then on up to the workspace root of the Astryx project it belongs to.+ * In each folder a `packages/core` whose package.json names+ * @astryxdesign/core (the Astryx repository's own source) comes first, then+ * an installed `node_modules/@astryxdesign/core`. It takes the first it finds,+ * whatever version the project declares: that is the copy Node loads. When no+ * folder holds one, it asks Yarn Plug'n'Play, which keeps no node_modules.+ *+ * @param {string} startDir+ * @returns {string|null} the Core package directory, or null when there is none+ */+function findNearbyCoreDir(startDir) {+ for (const dir of readFolders(startDir, CORE_REACH)) {+ const source = path.join(dir, 'packages', 'core');+ if (isCoreSource(source)) return source;+ const installed = installedIn(dir, CORE_PACKAGE);+ if (installed) return installed;+ }+ return findPnpPackage(startDir, CORE_PACKAGE);+}+/*** Where Yarn's Plug'n'Play runtime says a package lives.*- * A PnP project has no node_modules for the walk below to find. PnP answers- * from the project's own dependency graph and ignores NODE_PATH, so asking it- * keeps the lookup project-local. Outside a PnP process there is nothing to ask.+ * A PnP project has no node_modules for the walks in this file to find. PnP+ * answers from the project's own dependency graph and ignores NODE_PATH, so+ * asking it keeps the lookup project-local. Outside a PnP process there is+ * nothing to ask.** @param {string} startDir* @param {string} name@@ -211,8 +641,9 @@ function findNearbyCoreDir(startDir) {function findPnpPackage(startDir, name) {if (!process.versions.pnp) return null;try {- const api = createRequire(path.join(startDir, 'noop.js'))('pnpapi');- const dir = api.resolveToUnqualified(name, path.join(startDir, '/'));+ const from = path.resolve(startDir);+ const api = createRequire(path.join(from, 'noop.js'))('pnpapi');+ const dir = api.resolveToUnqualified(name, path.join(from, '/'));return dir && fs.existsSync(path.join(dir, 'package.json')) ? dir : null;} catch {// The project does not declare it, or this is not a PnP process after all.@@ -220,6 +651,24 @@ function findPnpPackage(startDir, name) {}}+/**+ * The nearest `node_modules/<name>` at or above `startDir`, found the way+ * Node's resolver finds a package, and the folder whose node_modules holds it.+ * It searches every folder up to the filesystem root and does not ask+ * Plug'n'Play.+ *+ * @param {string} startDir+ * @param {string} name bare package name; callers reject path segments first+ * @returns {{packageDir: string, hostDir: string}|null}+ */+export function findNodeModulesPackage(startDir, name) {+ for (const dir of foldersUpFrom(startDir)) {+ const packageDir = installedIn(dir, name);+ if (packageDir) return {packageDir, hostDir: dir};+ }+ return null;+}+/*** Locate a package the project at `startDir` actually installed.*@@ -231,25 +680,67 @@ function findPnpPackage(startDir, name) {* Reading package.json off disk also sidesteps packages that don't export it,* so the version is always available to range-check.*- * Walks the node_modules chain first, then asks PnP, which covers the Yarn- * default layout where that chain does not exist.+ * Searches the node_modules of `startDir` and the five folders above it, as+ * released versions did, then on up to the workspace root of the Astryx+ * project it belongs to. Then it asks PnP, which covers the Yarn default+ * layout where that chain does not exist.** @param {string} startDir* @param {string} name* @returns {string|null} the package directory, or null when not installed*/export function findInstalledPackage(startDir, name) {- let dir = startDir;- for (let i = 0; i < 6; i++) {- const candidate = path.join(dir, 'node_modules', ...name.split('/'));- if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;- const parent = path.dirname(dir);- if (parent === dir) break;- dir = parent;+ for (const dir of readFolders(startDir, INSTALLED_REACH)) {+ const packageDir = installedIn(dir, name);+ if (packageDir) return packageDir;}return findPnpPackage(startDir, name);}+/**+ * The first of `names` the Astryx project of `startDir` installed, for a+ * command that writes to the project (`upgrade`).+ *+ * It searches the node_modules of the project root, nearest name first. For+ * a member its workspace lists, it then searches each folder above the+ * project up to the workspace root, where the workspace installs the packages+ * its members share; otherwise the search stops at the project root. Then it+ * asks Plug'n'Play, in name order. With no Astryx project it looks only in the+ * node_modules of `startDir` itself, as released versions did.+ *+ * @param {string} startDir+ * @param {readonly string[]} names in order of preference+ * @returns {{name: string, packageDir: string}|null}+ */+export function findProjectPackageOf(startDir, names) {+ const project = findAstryxProject(startDir);+ if (project == null) {+ const dir = path.resolve(startDir);+ for (const name of names) {+ const packageDir = installedIn(dir, name);+ if (packageDir) return {name, packageDir};+ }+ return null;+ }+ const workspace = workspaceBound(project);+ const top =+ workspace !== project && isWorkspaceMember(project, workspace)+ ? workspace+ : project;+ for (const dir of foldersUpFrom(project)) {+ for (const name of names) {+ const packageDir = installedIn(dir, name);+ if (packageDir) return {name, packageDir};+ }+ if (dir === top) break;+ }+ for (const name of names) {+ const packageDir = findPnpPackage(project, name);+ if (packageDir) return {name, packageDir};+ }+ return null;+}+/*** Find the monorepo root by looking for the root package.json* that has workspaces defined.diff --git a/packages/cli/foundation/fs/paths.test.mjs b/packages/cli/foundation/fs/paths.test.mjsindex 7fdcef4cef..93e5658645 100644--- a/packages/cli/foundation/fs/paths.test.mjs+++ b/packages/cli/foundation/fs/paths.test.mjs@@ -4,7 +4,7 @@ import {describe, it, expect, beforeEach, afterEach} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';-import {findCoreDir, findProjectCoreDir, findProjectRoot, listComponents, discoverExternalPackages, existsCaseExact, findInstalledPackage} from './paths.mjs';+import {findAstryxProject, findCoreDir, findProjectCoreDir, findProjectRoot, listComponents, discoverExternalPackages, existsCaseExact, findInstalledPackage, findNodeModulesPackage, findPackageRoot, findProjectPackageOf, findWorkspaceRoot} from './paths.mjs';import {CLI_ROOT} from './paths.mjs';import {linkThisCliAsProjectCli} from '../../test-utils/release-fixtures.mjs';@@ -19,13 +19,93 @@ beforeEach(() => {});afterEach(() => {+ delete process.versions.pnp;fs.rmSync(tmpDir, {recursive: true, force: true});});+/**+ * Write a package.json naming `name` into `dir`, creating the folder.+ * @param {string} dir @param {string} name @param {string} [version]+ */+function writePackage(dir, name, version = '0.7.0') {+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({name, version}));+ return dir;+}++/**+ * Write a project package.json into `dir`, creating the folder.+ * @param {string} dir @param {Record<string, unknown>} [fields]+ */+function writeProject(dir, fields = {}) {+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({name: path.basename(dir), ...fields}));+ return dir;+}++/**+ * Run `fn` with `home` as the home folder.+ * @template T+ * @param {string} home @param {() => T} fn+ * @returns {T}+ */+function withHome(home, fn) {+ const previous = process.env.HOME;+ process.env.HOME = home;+ try {+ return fn();+ } finally {+ if (previous === undefined) delete process.env.HOME;+ else process.env.HOME = previous;+ }+}++/** Declares Core, which makes a package.json an Astryx project. */+const DECLARES_CORE = {dependencies: {'@astryxdesign/core': '^0.7.0'}};++/** @param {string} root @param {string} name @param {string} version */+function install(root, name, version) {+ return writePackage(path.join(root, 'node_modules', ...name.split('/')), name, version);+}++/**+ * Stand in for the runtime a Yarn Plug'n'Play process exposes:+ * `process.versions.pnp` plus a requirable `pnpapi`. The packages themselves+ * live outside any node_modules, the way Yarn stores them. The top-level+ * afterEach removes `process.versions.pnp` again.+ * @param {Record<string, string>} resolved name -> package directory+ * @returns {string} a project folder inside the PnP runtime+ */+function withPnp(resolved) {+ const runtime = path.join(tmpDir, 'runtime');+ const api = path.join(runtime, 'node_modules', 'pnpapi');+ fs.mkdirSync(api, {recursive: true});+ fs.writeFileSync(+ path.join(api, 'package.json'),+ JSON.stringify({name: 'pnpapi', version: '1.0.0', main: 'index.js'}),+ );+ fs.writeFileSync(+ path.join(api, 'index.js'),+ `const resolved = ${JSON.stringify(resolved)};\n` ++ 'module.exports = {\n' ++ ' resolveToUnqualified(name) {\n' ++ ' if (!(name in resolved)) {\n' ++ " const e = new Error(name); e.code = 'MODULE_NOT_FOUND'; throw e;\n" ++ ' }\n' ++ ' return resolved[name];\n' ++ ' },\n' ++ '};\n',+ );+ Object.defineProperty(process.versions, 'pnp', {+ value: '3',+ configurable: true,+ });+ return runtime;+}+describe('findCoreDir', () => {it('finds packages/core walking up directories', () => {- const coreDir = path.join(tmpDir, 'packages', 'core');- fs.mkdirSync(coreDir, {recursive: true});+ const coreDir = writePackage(path.join(tmpDir, 'packages', 'core'), '@astryxdesign/core');const nested = path.join(tmpDir, 'sub', 'deep');fs.mkdirSync(nested, {recursive: true});@@ -34,8 +114,7 @@ describe('findCoreDir', () => {});it('finds node_modules/@astryxdesign/core fallback', () => {- const nmCore = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');- fs.mkdirSync(nmCore, {recursive: true});+ const nmCore = install(tmpDir, '@astryxdesign/core', '0.7.0');expect(findCoreDir(tmpDir)).toBe(nmCore);});@@ -48,22 +127,111 @@ describe('findCoreDir', () => {// This copy's carried Core is the workspace Core beside it.expect(findCoreDir(tmpDir)).toBe(path.resolve(CLI_ROOT, '..', 'core'));linkThisCliAsProjectCli(tmpDir);- expect(findCoreDir(tmpDir)).toBeNull();+ // The project's own Core: findCoreDir falls back to the carried one.+ expect(findProjectCoreDir(tmpDir)).toBeNull();+ });++ // A route folder such as src/app/(shop)/orders/[id]/edit sits six folders+ // below the project root, where Core is installed.+ it('finds Core from any depth inside the project that installs it', () => {+ writeProject(tmpDir, {dependencies: {'@astryxdesign/core': '^0.7.0'}});+ const nmCore = install(tmpDir, '@astryxdesign/core', '0.7.0');+ const route = path.join(tmpDir, 'src', 'app', '(shop)', 'orders', '[id]', 'edit');+ fs.mkdirSync(route, {recursive: true});++ expect(findCoreDir(route)).toBe(nmCore);+ });++ it('searches a workspace up to its root from any depth in a member', () => {+ writeProject(tmpDir, {private: true, workspaces: ['apps/*']});+ const nmCore = install(tmpDir, '@astryxdesign/core', '0.7.0');+ const member = writeProject(path.join(tmpDir, 'apps', 'web'), {dependencies: {'@astryxdesign/core': '^0.7.0'}});+ const route = path.join(member, 'src', 'app', '(shop)', 'orders', '[id]');+ fs.mkdirSync(route, {recursive: true});++ expect(findCoreDir(route)).toBe(nmCore);+ });++ it('searches only the folder and the four above it outside any Astryx project', () => {+ install(tmpDir, '@astryxdesign/core', '0.7.0');+ const project = writeProject(path.join(tmpDir, 'a', 'b', 'c', 'd', 'e', 'app'));++ // The project's own Core: findCoreDir falls back to the carried one.+ expect(findProjectCoreDir(project)).toBeNull();+ });++ // A package.json that only sets the module type is not the project, so a+ // folder deep below it still reaches the Core the project installs.+ it('looks past a nested package.json that declares no Astryx package', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const nmCore = install(tmpDir, '@astryxdesign/core', '0.7.0');+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'src', 'package.json'), JSON.stringify({type: 'module'}));+ const deep = path.join(tmpDir, 'src', 'l1', 'l2', 'l3', 'l4', 'l5', 'l6');+ fs.mkdirSync(deep, {recursive: true});++ expect(findCoreDir(deep)).toBe(nmCore);+ });++ // Past the reach the search starts at the project root: a tool folder+ // between them that installs its own Core but declares nothing never+ // answers for the project, as `upgrade` targets the project's Core.+ it('answers the project\'s Core, not a tool folder\'s, from deep inside the tool', () => {+ const app = path.join(tmpDir, 'app');+ writeProject(app, DECLARES_CORE);+ const projectCore = install(app, '@astryxdesign/core', '0.7.0');+ const tool = path.join(app, 'tools', 'codegen');+ writePackage(tool, 'codegen');+ install(tool, '@astryxdesign/core', '0.9.0');+ const deep = path.join(tool, 'src', 'a', 'b', 'c', 'd', 'e');+ fs.mkdirSync(deep, {recursive: true});++ expect(findProjectCoreDir(deep)).toBe(projectCore);+ expect(findInstalledPackage(path.join(deep, 'f'), '@astryxdesign/core')).toBe(projectCore);+ });++ // Node loads the hoisted copy whatever the member declares: an override or+ // resolution can force it, and a peer range can be stale. Reads answer from+ // the copy that loads.+ it.each([+ ['a range the copy is outside of', {devDependencies: {'@astryxdesign/core': '~0.6.8'}}],+ ['only a stale peer range', {peerDependencies: {'@astryxdesign/core': '^0.6.8'}}],+ ])('takes a workspace Core when the member declares %s', (_label, fields) => {+ writeProject(tmpDir, {private: true, workspaces: ['apps/*'], overrides: {'@astryxdesign/core': '0.7.1'}});+ const nmCore = install(tmpDir, '@astryxdesign/core', '0.7.1');+ const member = writeProject(path.join(tmpDir, 'apps', 'web'), fields);++ expect(findCoreDir(member)).toBe(nmCore);+ });++ it('skips a packages/core folder that holds another package', () => {+ writePackage(path.join(tmpDir, 'packages', 'core'), '@acme/core', '1.0.0');+ const app = path.join(tmpDir, 'apps', 'web');+ fs.mkdirSync(app, {recursive: true});++ // The project's own Core: findCoreDir falls back to the carried one.+ expect(findProjectCoreDir(app)).toBeNull();++ const nmCore = install(tmpDir, '@astryxdesign/core', '0.7.0');+ expect(findCoreDir(app)).toBe(nmCore);+ });++ it('skips a node_modules/@astryxdesign/core folder with no package.json', () => {+ fs.mkdirSync(path.join(tmpDir, 'node_modules', '@astryxdesign', 'core'), {recursive: true});++ // The project's own Core: findCoreDir falls back to the carried one.+ expect(findProjectCoreDir(tmpDir)).toBeNull();+ });++ it("asks Yarn Plug'n'Play when no folder holds Core", () => {+ const store = writePackage(path.join(tmpDir, 'store', '@astryxdesign-core'), '@astryxdesign/core');+ const project = withPnp({'@astryxdesign/core': store});++ expect(findCoreDir(project)).toBe(store);});});describe('findInstalledPackage', () => {- /** @param {string} root @param {string} name @param {string} version */- function install(root, name, version) {- const dir = path.join(root, 'node_modules', ...name.split('/'));- fs.mkdirSync(dir, {recursive: true});- fs.writeFileSync(- path.join(dir, 'package.json'),- JSON.stringify({name, version}),- );- return dir;- }-it('finds a package in the node_modules chain above startDir', () => {const installed = install(tmpDir, '@astryxdesign/core', '0.6.0');const nested = path.join(tmpDir, 'src', 'deep');@@ -72,6 +240,22 @@ describe('findInstalledPackage', () => {expect(findInstalledPackage(nested, '@astryxdesign/core')).toBe(installed);});+ it('finds a package from any depth inside the project', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const installed = install(tmpDir, '@astryxdesign/core', '0.7.0');+ const deep = path.join(tmpDir, 'apps', 'web', 'src', 'app', '(shop)', 'orders', '[id]');+ fs.mkdirSync(deep, {recursive: true});++ expect(findInstalledPackage(deep, '@astryxdesign/core')).toBe(installed);+ });++ it('does not search past six folders outside the project', () => {+ install(tmpDir, '@astryxdesign/core', '0.7.0');+ const project = writeProject(path.join(tmpDir, 'a', 'b', 'c', 'd', 'e', 'f', 'app'));++ expect(findInstalledPackage(project, '@astryxdesign/core')).toBeNull();+ });+it('reports a package the project never installed as missing', () => {expect(findInstalledPackage(tmpDir, '@astryxdesign/core')).toBeNull();});@@ -96,43 +280,6 @@ describe('findInstalledPackage', () => {});describe('under Yarn Plug\'n\'Play, which has no node_modules', () => {- /**- * Stand in for the runtime a PnP process exposes: `process.versions.pnp`- * plus a requirable `pnpapi`. The package itself lives outside any- * node_modules, the way Yarn stores it.- * @param {Record<string, string>} resolved name -> package directory- */- function withPnp(resolved) {- const runtime = path.join(tmpDir, 'runtime');- const api = path.join(runtime, 'node_modules', 'pnpapi');- fs.mkdirSync(api, {recursive: true});- fs.writeFileSync(- path.join(api, 'package.json'),- JSON.stringify({name: 'pnpapi', version: '1.0.0', main: 'index.js'}),- );- fs.writeFileSync(- path.join(api, 'index.js'),- `const resolved = ${JSON.stringify(resolved)};\n` +- 'module.exports = {\n' +- ' resolveToUnqualified(name) {\n' +- ' if (!(name in resolved)) {\n' +- " const e = new Error(name); e.code = 'MODULE_NOT_FOUND'; throw e;\n" +- ' }\n' +- ' return resolved[name];\n' +- ' },\n' +- '};\n',- );- Object.defineProperty(process.versions, 'pnp', {- value: '3',- configurable: true,- });- return runtime;- }-- afterEach(() => {- delete process.versions.pnp;- });-it('falls back to the PnP runtime when there is no chain to walk', () => {const store = path.join(tmpDir, 'store', '@astryxdesign-core');fs.mkdirSync(store, {recursive: true});@@ -153,6 +300,235 @@ describe('findInstalledPackage', () => {});});+describe('findProjectPackageOf', () => {+ const NAMES = ['@astryxdesign/core', '@xds/core'];++ it('takes the earlier name when one folder installs both', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const current = install(tmpDir, '@astryxdesign/core', '0.7.0');+ install(tmpDir, '@xds/core', '0.3.0');++ expect(findProjectPackageOf(tmpDir, NAMES)).toEqual({name: '@astryxdesign/core', packageDir: current});+ });++ it('takes the nearest folder over an earlier name further up', () => {+ writeProject(tmpDir, {private: true, workspaces: ['apps/*']});+ install(tmpDir, '@astryxdesign/core', '0.7.0');+ const member = writeProject(path.join(tmpDir, 'apps', 'legacy'), {dependencies: {'@xds/core': '0.3.0'}});+ const legacy = install(member, '@xds/core', '0.3.0');++ expect(findProjectPackageOf(member, NAMES)).toEqual({name: '@xds/core', packageDir: legacy});+ });++ it('returns null when none is installed', () => {+ expect(findProjectPackageOf(tmpDir, NAMES)).toBeNull();+ });++ it('finds the package from a subfolder of the project', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const current = install(tmpDir, '@astryxdesign/core', '0.7.0');+ const deep = path.join(tmpDir, 'src', 'l1', 'l2');+ fs.mkdirSync(deep, {recursive: true});++ expect(findProjectPackageOf(deep, NAMES)).toEqual({name: '@astryxdesign/core', packageDir: current});+ });++ // A member uses what its workspace installs, whatever its own package.json+ // says: an override or resolution can force the copy, and a range or peer+ // range can be stale. Membership decides, not the declared version.+ it.each([+ ['~0.6.8', 'dependencies'],+ ['0.7.0 - 0.8.0', 'dependencies'],+ ['>= 0.7.0', 'dependencies'],+ ['^0.6.8', 'peerDependencies'],+ ])('takes the hoisted package for a member that declares %s in %s', (range, field) => {+ writeProject(tmpDir, {private: true, workspaces: ['apps/*']});+ const hoisted = install(tmpDir, '@astryxdesign/core', '0.7.1');+ const member = writeProject(path.join(tmpDir, 'apps', 'web'), {[field]: {'@astryxdesign/core': range}});++ expect(findProjectPackageOf(member, NAMES)).toEqual({name: '@astryxdesign/core', packageDir: hoisted});+ });++ it.each([+ ['Yarn object-form workspaces', {workspaces: {packages: ['apps/*']}}, null],+ ['a ** pattern', {workspaces: ['apps/**']}, null],+ ['a brace pattern', {workspaces: ['{apps,tools}/*']}, null],+ ['a brace list of globs', {workspaces: ['{apps/*,tools/*}']}, null],+ ['a nested brace list', {workspaces: ['{apps/{web,admin},tools/*}']}, null],+ ['a pnpm-workspace.yaml block list', {}, "packages:\n - 'apps/*' # apps\n - \"tools/*\"\nonlyBuiltDependencies: []\n"],+ ['a pnpm-workspace.yaml flow list', {}, "packages: ['tools/*', apps/*]\n"],+ ])('takes the hoisted package for a member that %s lists', (_label, rootFields, yaml) => {+ writeProject(tmpDir, {private: true, ...rootFields});+ if (yaml) fs.writeFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), yaml);+ const hoisted = install(tmpDir, '@astryxdesign/core', '0.7.1');+ const member = writeProject(path.join(tmpDir, 'apps', 'web'), DECLARES_CORE);++ expect(findProjectPackageOf(member, NAMES)).toEqual({name: '@astryxdesign/core', packageDir: hoisted});+ });++ it.each([+ ['lists other folders', {workspaces: ['packages/*']}],+ ['excludes it with a ! pattern', {workspaces: ['apps/*', '!apps/web']}],+ ['lists other folders in a brace list of globs', {workspaces: ['{packages/*,tools/*}']}],+ ])('stops at the project root when the workspace %s', (_label, rootFields) => {+ writeProject(tmpDir, {private: true, ...rootFields});+ install(tmpDir, '@astryxdesign/core', '0.7.1');+ const project = writeProject(path.join(tmpDir, 'apps', 'web'), DECLARES_CORE);++ expect(findProjectPackageOf(project, NAMES)).toBeNull();+ });++ // AST-040 FR11: a Plug'n'Play project that declares Core keeps no+ // node_modules copy; the runtime answers for it.+ it("asks Yarn Plug'n'Play for a project that declares Core and has no node_modules copy", () => {+ const store = writePackage(path.join(tmpDir, 'store', '@astryxdesign-core'), '@astryxdesign/core', '0.7.1');+ const project = withPnp({'@astryxdesign/core': store});+ writeProject(project, DECLARES_CORE);++ expect(fs.existsSync(path.join(project, 'node_modules', '@astryxdesign'))).toBe(false);+ expect(findProjectPackageOf(project, NAMES)).toEqual({name: '@astryxdesign/core', packageDir: store});+ });++ // A project nested in another, outside any workspace, has its own install.+ it('stops at the root of a nested project outside any workspace', () => {+ writeProject(tmpDir, {dependencies: {'@astryxdesign/core': '0.8.0'}});+ install(tmpDir, '@astryxdesign/core', '0.8.0');+ const nested = writeProject(path.join(tmpDir, 'apps', 'web'), {dependencies: {'@astryxdesign/core': '0.9.0'}});++ expect(findProjectPackageOf(nested, NAMES)).toBeNull();+ });++ // With no Astryx project, released versions read only this folder's own+ // node_modules.+ it('reads only the folder itself when no Astryx project contains it', () => {+ writeProject(tmpDir);+ install(tmpDir, '@astryxdesign/core', '0.7.1');+ const plain = writeProject(path.join(tmpDir, 'plain'));++ expect(findProjectPackageOf(plain, NAMES)).toBeNull();+ const own = install(plain, '@astryxdesign/core', '0.7.1');+ expect(findProjectPackageOf(plain, NAMES)).toEqual({name: '@astryxdesign/core', packageDir: own});+ });+});++describe('findAstryxProject', () => {+ it('is the nearest folder whose package.json declares an Astryx package', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const tool = writeProject(path.join(tmpDir, 'tools', 'lint'));+ const deep = path.join(tool, 'src');+ fs.mkdirSync(deep, {recursive: true});++ expect(findAstryxProject(deep)).toBe(tmpDir);+ const app = writeProject(path.join(tmpDir, 'apps', 'web'), {devDependencies: {'@astryxdesign/cli': '0.7.1'}});+ expect(findAstryxProject(app)).toBe(app);+ });++ it('counts a peer declaration and the legacy scope', () => {+ const integration = writeProject(path.join(tmpDir, 'integration'), {peerDependencies: {'@astryxdesign/core': '^0.7.0'}});+ const legacy = writeProject(path.join(tmpDir, 'legacy'), {dependencies: {'@xds/core': '0.3.0'}});++ expect(findAstryxProject(integration)).toBe(integration);+ expect(findAstryxProject(legacy)).toBe(legacy);+ });++ it('stops at a repository root', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const repo = writeProject(path.join(tmpDir, 'repo'));+ fs.mkdirSync(path.join(repo, '.git'));+ const tools = path.join(repo, 'tools');+ fs.mkdirSync(tools, {recursive: true});++ expect(findAstryxProject(tools)).toBeNull();+ });++ it('never counts the home folder', () => {+ writeProject(tmpDir, DECLARES_CORE);+ const desktop = path.join(tmpDir, 'Desktop');+ fs.mkdirSync(desktop, {recursive: true});++ withHome(tmpDir, () => {+ expect(findAstryxProject(desktop)).toBeNull();+ expect(findAstryxProject(tmpDir)).toBeNull();+ });+ });++ it('returns null when no folder declares Astryx', () => {+ writeProject(tmpDir);++ expect(findAstryxProject(tmpDir)).toBeNull();+ });++ it('counts a member its workspace lists when the workspace root declares Astryx', () => {+ writeProject(tmpDir, {private: true, workspaces: ['apps/*'], ...DECLARES_CORE});+ const member = writeProject(path.join(tmpDir, 'apps', 'web'));+ const tests = writeProject(path.join(member, 'e2e'));++ expect(findAstryxProject(path.join(member, 'src'))).toBe(member);+ expect(findAstryxProject(tests)).toBe(member);+ const other = writeProject(path.join(tmpDir, 'tools', 'lint'));+ expect(findAstryxProject(other)).toBe(tmpDir);+ });+});++describe('findPackageRoot', () => {+ it('finds the nearest package.json at or above the folder', () => {+ writeProject(tmpDir);+ const app = writeProject(path.join(tmpDir, 'apps', 'web'));+ const deep = path.join(app, 'src', 'app');+ fs.mkdirSync(deep, {recursive: true});++ expect(findPackageRoot(deep)).toBe(app);+ expect(findPackageRoot(tmpDir)).toBe(tmpDir);+ });++ it('returns null with no package.json', () => {+ expect(findPackageRoot(tmpDir)).toBeNull();+ });+});++describe('findWorkspaceRoot', () => {+ it('finds the nearest folder that declares workspaces in package.json', () => {+ writeProject(tmpDir, {private: true, workspaces: ['apps/*']});+ const member = writeProject(path.join(tmpDir, 'apps', 'web'));++ expect(findWorkspaceRoot(path.join(member, 'src'))).toBe(tmpDir);+ });++ it('finds the nearest folder with pnpm-workspace.yaml', () => {+ writeProject(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), "packages:\n - 'apps/*'\n");+ const member = writeProject(path.join(tmpDir, 'apps', 'web'));++ expect(findWorkspaceRoot(member)).toBe(tmpDir);+ });++ it('is the nearest package.json outside a workspace, and the folder itself with none', () => {+ const app = writeProject(path.join(tmpDir, 'app'));+ const src = path.join(app, 'src');+ fs.mkdirSync(src, {recursive: true});++ expect(findWorkspaceRoot(src)).toBe(app);+ expect(findWorkspaceRoot(tmpDir)).toBe(tmpDir);+ });+});++describe('findNodeModulesPackage', () => {+ it('finds a package hoisted to a workspace root and names the folder that holds it', () => {+ const hoisted = install(tmpDir, '@acme/widgets', '1.0.0');+ const member = path.join(tmpDir, 'apps', 'web');+ fs.mkdirSync(member, {recursive: true});++ expect(findNodeModulesPackage(member, '@acme/widgets')).toEqual({packageDir: hoisted, hostDir: tmpDir});+ });++ it('does not ask Plug\'n\'Play', () => {+ const store = writePackage(path.join(tmpDir, 'store', 'acme-widgets'), '@acme/widgets');+ const project = withPnp({'@acme/widgets': store});++ expect(findNodeModulesPackage(project, '@acme/widgets')).toBeNull();+ });+});+describe('findProjectRoot', () => {it('finds root with workspaces in package.json', () => {fs.writeFileSync(diff --git a/packages/cli/foundation/integrations/autolink.mjs b/packages/cli/foundation/integrations/autolink.mjsindex e2e8db3f2e..c7261e5acc 100644--- a/packages/cli/foundation/integrations/autolink.mjs+++ b/packages/cli/foundation/integrations/autolink.mjs@@ -39,6 +39,7 @@import * as fs from 'node:fs';import * as path from 'node:path';+import {findNodeModulesPackage} from '../fs/paths.mjs';import {findManifestPaths, loadIntegrations} from './integrations.mjs';import {resolveProviders} from './provider-resolution.mjs';@@ -123,7 +124,8 @@ export function readDeclaredDependencies(projectDir) {** Walking up matters because hoisting is normal — yarn and npm workspaces lift* a workspace member's dependency to the repo root, so the app's own- * node_modules can be empty of a package it genuinely declares.+ * node_modules can be empty of a package it genuinely declares. Integrations+ * named in astryx.config resolve through the same walk.** Presence is decided by the package's own package.json, not the directory, so* a stale empty directory is not mistaken for an install.@@ -135,18 +137,7 @@ export function readDeclaredDependencies(projectDir) {*/export function resolveInstalledPackageDir(name, fromDir) {if (!isBarePackageName(name)) return null;- const segments = name.split('/');- let dir = path.resolve(fromDir);- for (let i = 0; i < 50; i++) {- const packageDir = path.join(dir, 'node_modules', ...segments);- if (fs.existsSync(path.join(packageDir, 'package.json'))) {- return {packageDir, hostDir: dir};- }- const parent = path.dirname(dir);- if (parent === dir) break;- dir = parent;- }- return null;+ return findNodeModulesPackage(fromDir, name);}/**diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex e4057f71f4..4adac5411e 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -19,6 +19,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {assertWithin} from '../fs/path-safety.mjs';+import {findNodeModulesPackage} from '../fs/paths.mjs';import {normalizeProviderId} from '../identity/provider-identity.mjs';// The key census and contribution parsers are internal to the schema module on// purpose: the public parser still validates the complete authored type, while@@ -368,6 +369,25 @@ export function resolvePackageDir(packageName, cwd = process.cwd()) {return dir;}+/**+ * Where an integration named in astryx.config is installed: the nearest+ * `node_modules/<name>` at or above `cwd`, found the way an autolinked+ * dependency is, so a package a workspace hoists to its root loads in every+ * member. When it is installed nowhere, `cwd`'s own `node_modules/<name>`,+ * which the caller reports as not installed.+ * @param {string} packageName+ * @param {string} [cwd]+ * @returns {string}+ */+export function resolveInstalledIntegrationDir(+ packageName,+ cwd = process.cwd(),+) {+ // Validates the name first: it throws on a spec with path segments.+ const ownDir = resolvePackageDir(packageName, cwd);+ return findNodeModulesPackage(cwd, packageName)?.packageDir ?? ownDir;+}+/*** Find the single conventional root manifest sibling of the package's* package.json. Multiple present is a hard error; missing is a hard error.@@ -531,7 +551,7 @@ export async function loadIntegrations(if (!spec || seenSpecs.has(spec)) continue;seenSpecs.add(spec);- const packageDir = resolvePackageDir(spec, cwd);+ const packageDir = resolveInstalledIntegrationDir(spec, cwd);const pkgPath = path.join(packageDir, 'package.json');let pkg;try {