An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): keep the other integrations when one cannot load (#6519)
Joeyed10d9776ad1
diff --git a/.changeset/cli-spec-isolate-broken-integrations.md b/.changeset/cli-spec-isolate-broken-integrations.mdnew file mode 100644index 0000000000..02f1c1368c--- /dev/null+++ b/.changeset/cli-spec-isolate-broken-integrations.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] One integration that cannot load at all (a configured package that is not installed, has no manifest or more than one, or a package being authored with two manifests) no longer takes every other integration down with it. It is reported as that package's integration issue, the other integrations keep contributing, and `astryx discover` no longer exits 1 because of it.++@josephfarinadiff --git a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjsindex 7068c73077..7af13d118f 100644--- a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs+++ b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs@@ -87,6 +87,54 @@ describe('astryx discover with a manifest that fails to load', () => {});});+describe('astryx discover with a configured package that is not installed', () => {+ beforeEach(() => {+ const healthy = path.join(project, 'node_modules', '@test', 'healthy');+ fs.mkdirSync(path.join(healthy, 'components'), {recursive: true});+ fs.writeFileSync(+ path.join(healthy, 'package.json'),+ JSON.stringify({name: '@test/healthy', version: '2.0.0'}),+ );+ fs.writeFileSync(+ path.join(healthy, 'astryx.integration.mjs'),+ `export default {components: './components'};\n`,+ );+ fs.writeFileSync(+ path.join(healthy, 'components', 'Widget.doc.mjs'),+ `export const docs = {name: 'Widget', usage: {description: 'A widget.'}};\n`,+ );+ fs.writeFileSync(+ path.join(healthy, 'components', 'Widget.tsx'),+ `export function Widget() { return null; }\n`,+ );+ fs.writeFileSync(+ path.join(project, 'astryx.config.mjs'),+ `export default {integrations: ['@test/missing', '@test/healthy']};\n`,+ );+ });++ it('still lists the healthy package and exits 0', async () => {+ const {status, stdout} = await runCli(['discover', '--json'], {+ cwd: project,+ });++ expect(status).toBe(0);+ expect(JSON.parse(stdout).data).toEqual([+ expect.objectContaining({name: '@test/healthy', components: ['Widget']}),+ ]);+ });++ it('names the missing package in the stderr nudge', async () => {+ const {status, stderr} = await runCli(['discover'], {cwd: project});++ expect(status).toBe(0);+ expect(stderr).toContain(+ 'Warning: @test/missing has 1 integration issue(s). ' ++ 'Run: astryx doctor integration validate @test/missing',+ );+ });+});+describe('astryx search with a manifest that fails to load', () => {// search needs a resolvable @astryxdesign/core; without one it errors out// before it can list anything, which is not the case under test.diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex a24f9927ac..2ca4d1234e 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -39,6 +39,7 @@ import {loadIntegrations,loadLocalIntegration,markProviderConflicts,+ resolvePackageDir,} from '../integrations/integrations.mjs';import {autolinkIntegrations} from '../integrations/autolink.mjs';import {@@ -95,6 +96,118 @@ function errorMessage(err) {return message == null ? String(err) : String(message);}+/**+ * Load the configured integrations one at a time, so a package that cannot+ * load at all (not installed, no manifest, more than one manifest, not a bare+ * name) becomes that entry's load-error marker instead of failing the project.+ * @param {string[]} specs+ * @param {{cwd: string, fresh: boolean}} options+ * @returns {Promise<import('../integrations/integrations.mjs').LoadedIntegration[]>}+ */+async function loadConfiguredIntegrations(specs, {cwd, fresh}) {+ /** @type {import('../integrations/integrations.mjs').LoadedIntegration[]} */+ const loaded = [];+ const seen = new Set();+ for (const spec of specs) {+ if (!spec || seen.has(spec)) continue;+ seen.add(spec);+ try {+ loaded.push(+ ...(await loadIntegrations([spec], {+ cwd,+ fresh,+ resolveProviders: false,+ })),+ );+ } catch (err) {+ /** @type {string|undefined} */+ let packageDir;+ try {+ packageDir = resolvePackageDir(spec, cwd);+ } catch {+ // Not a bare package name: there is no install location to record.+ }+ const pkg = packageDir ? readPackageJson(packageDir) : null;+ loaded.push(+ loadErrorMarker({+ name: packageName(pkg) ?? spec,+ version: pkg?.version,+ spec,+ packageDir,+ err,+ }),+ );+ }+ }+ return loaded;+}++/**+ * Resolve the package being authored. Every failure, including an unreadable+ * package.json or more than one manifest, becomes its load-error marker.+ * @param {string} projectDir+ * @param {boolean} fresh+ * @returns {Promise<import('../integrations/integrations.mjs').LoadedIntegration|null>}+ */+async function loadLocalIntegrationSafely(projectDir, fresh) {+ try {+ return await loadLocalIntegration(projectDir, {fresh});+ } catch (err) {+ const pkg = readPackageJson(projectDir);+ const name = packageName(pkg) ?? '(local integration)';+ return {+ ...loadErrorMarker({+ name,+ version: pkg?.version,+ spec: name,+ packageDir: projectDir,+ err,+ }),+ __local: true,+ };+ }+}++/**+ * An inert entry for an integration that could not be loaded. It contributes+ * nothing; Project reports its `__loadError` as the package's issue.+ * @param {{name: string, version?: unknown, spec: string, packageDir?: string, err: unknown}} input+ * @returns {import('../integrations/integrations.mjs').LoadedIntegration}+ */+function loadErrorMarker({name, version, spec, packageDir, err}) {+ return /** @type {import('../integrations/integrations.mjs').LoadedIntegration} */ ({+ name,+ ...(typeof version === 'string' ? {version} : {}),+ __spec: spec,+ ...(packageDir ? {__packageDir: packageDir} : {}),+ __loadError: errorMessage(err),+ });+}++/**+ * @param {Record<string, unknown>|null} pkg+ * @returns {string|undefined}+ */+function packageName(pkg) {+ const name = pkg?.name;+ return typeof name === 'string' && name.length > 0 ? name : undefined;+}++/**+ * @param {string} dir+ * @returns {Record<string, unknown>|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;+ }+}+/*** An integration issue tagged with the owner package. The base* {@link import('../integrations/issue').AstryxIntegrationIssue} fields plus the@@ -276,11 +389,10 @@ export class Project {fresh,});integrations = config.integrations ?? [];- loadedIntegrations = await loadIntegrations(integrations, {+ // Provider identity is resolved once, below, over the final set.+ loadedIntegrations = await loadConfiguredIntegrations(integrations, {cwd: projectDir,fresh,- // Provider identity is resolved once, below, over the final set.- resolveProviders: false,});}@@ -305,7 +417,7 @@ export class Project {// existing consumer command doubles as the author's preview. A local copy// replaces the same installed package in place, preserving configured// precedence while making the source being edited authoritative.- const localIntegration = await loadLocalIntegration(projectDir, {fresh});+ const localIntegration = await loadLocalIntegrationSafely(projectDir, fresh);if (localIntegration) {const existing = loadedIntegrations.findIndex(integration => integration.name === localIntegration.name,diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex 04eff568f1..98abe649ed 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -515,6 +515,132 @@ describe('Project issues (skip + warn)', () => {});});+describe('Project loads each integration in isolation', () => {+ /**+ * Install a package under node_modules with the given root files.+ * @param {string} name+ * @param {string[]} manifests manifest basenames to write+ */+ function installPackage(name, manifests) {+ const dir = path.join(tmpDir, 'node_modules', ...name.split('/'));+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version: '1.0.0'}),+ );+ for (const file of manifests) {+ fs.writeFileSync(path.join(dir, file), 'export default {};\n');+ }+ }++ /** @param {string[]} integrations */+ function writeConfig(integrations) {+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ `export default ${JSON.stringify({integrations})};\n`,+ );+ }++ /** @param {Project} project */+ async function widgetComponents(project) {+ return (await project.components())+ .filter(component => component.package === '@acme/widgets')+ .map(component => component.name);+ }++ it.each([+ ['is not installed', '@acme/broken', () => {}, /Install it first/],+ [+ 'has no root manifest',+ '@acme/broken',+ () => installPackage('@acme/broken', []),+ /no conventional root manifest/,+ ],+ [+ 'has two root manifests',+ '@acme/broken',+ () =>+ installPackage('@acme/broken', [+ 'astryx.integration.mjs',+ 'astryx.integration.js',+ ]),+ /multiple root manifests/,+ ],+ [+ 'is not a bare package name',+ '../escape',+ () => {},+ /Invalid integration package name/,+ ],+ ])(+ 'keeps the others when a configured package %s',+ async (_label, spec, install, message) => {+ scaffold();+ install();+ writeConfig([spec, '@acme/widgets']);++ const project = await Project.load(tmpDir);++ expect(await widgetComponents(project)).toEqual(['Widget']);+ expect(await project.issues()).toContainEqual(+ expect.objectContaining({+ package: spec,+ code: 'integration_error',+ message: expect.stringMatching(message),+ }),+ );+ },+ );++ it('keeps configured integrations when the package being authored has two root manifests', async () => {+ scaffold();+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/local', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.js'),+ 'export default {};\n',+ );++ const project = await Project.load(tmpDir);++ expect(await widgetComponents(project)).toEqual(['Widget']);+ expect(await project.issues()).toContainEqual(+ expect.objectContaining({+ package: '@acme/local',+ code: 'integration_error',+ message: expect.stringMatching(/multiple root manifests/),+ }),+ );+ });++ it('puts the package being authored at its configured position when the config names it', async () => {+ scaffold();+ scaffoldLocalPackage({name: '@acme/local'});+ writeConfig(['@acme/local', '@acme/widgets']);++ const project = await Project.load(tmpDir);++ expect(+ project.loadedIntegrations.map(integration => [+ integration.name,+ Boolean(integration.__local),+ ]),+ ).toEqual([+ ['@acme/local', true],+ ['@acme/widgets', false],+ ]);+ expect(await project.issues()).not.toContainEqual(+ expect.objectContaining({package: '@acme/local', 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/integrations/autolink.mjs b/packages/cli/foundation/integrations/autolink.mjsindex 6246e7d228..63fd1fd0fb 100644--- a/packages/cli/foundation/integrations/autolink.mjs+++ b/packages/cli/foundation/integrations/autolink.mjs@@ -229,7 +229,12 @@ export async function autolinkIntegrations({fresh = false,}) {const candidates = findAutolinkCandidates(projectDir, {- exclude: loaded.map(integration => integration.__packageDir),+ // A configured entry that never resolved to a directory has none to exclude.+ exclude: loaded.flatMap(integration =>+ typeof integration.__packageDir === 'string'+ ? [integration.__packageDir]+ : [],+ ),});/** @type {import('./integrations.mjs').LoadedIntegration[]} */