An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): host entry for a tool that carries the CLI (#7420)
Joey2e9add0c9bdc
diff --git a/.changeset/cli-host-entry.md b/.changeset/cli-host-entry.mdnew file mode 100644index 0000000000..d82fedf97f--- /dev/null+++ b/.changeset/cli-host-entry.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feat] Add the `@astryxdesign/cli/host` entry: `runHostedCli` runs the CLI once per process for a tool that carries it, with the command name that tool's users type (printed commands start with it) and, when the tool skipped the project's own CLI, the reason, so that CLI is never run+@josephfarinadiff --git a/apps/docsite/src/__tests__/route-resolution.test.ts b/apps/docsite/src/__tests__/route-resolution.test.tsindex 9614e84b31..a881b656e0 100644--- a/apps/docsite/src/__tests__/route-resolution.test.ts+++ b/apps/docsite/src/__tests__/route-resolution.test.ts@@ -90,8 +90,9 @@ describe('route resolution', () => {it('lists the guides the sidebar listed before the splits, plus new topics only', () => {// The Guide section as it was before the CLI integration guide and the- // other topics were split into short guides. `styling-overview` is a- // topic added since; `global` is the Global mode page.+ // other topics were split into short guides. `styling-overview` and+ // `cli-host-entry` are topics added since; `global` is the Global mode+ // page.const sidebarGuides = docTopics.filter(d => d.category === 'guide' && d.topic !== 'getting-started').map(d => d.topic)@@ -101,6 +102,7 @@ describe('route resolution', () => {'authoring','browser-support','cli-component-lookups',+ 'cli-host-entry','cli-integrations','cli-writing-docs','global',diff --git a/internal/eslint-plugin-astryx/no-raw-console-cli.js b/internal/eslint-plugin-astryx/no-raw-console-cli.jsindex 7062942a12..f31289d873 100644--- a/internal/eslint-plugin-astryx/no-raw-console-cli.js+++ b/internal/eslint-plugin-astryx/no-raw-console-cli.js@@ -27,13 +27,15 @@* ban #1:* - packages/cli/foundation/response/json.mjs (defines humanLog / jsonOut)* - packages/cli/clients/cli/index.mjs (wiring / banner)- * - packages/cli/clients/cli/bin/astryx.mjs (entrypoint / error boundary)+ * - packages/cli/clients/cli/bin/astryx.mjs (entrypoint / Node gate)+ * - packages/cli/clients/cli/run.mjs (one run / error boundary)*/const EXEMPT_SUFFIXES = ['packages/cli/foundation/response/json.mjs','packages/cli/clients/cli/index.mjs','packages/cli/clients/cli/bin/astryx.mjs',+ 'packages/cli/clients/cli/run.mjs',];// Command files must funnel human output through emit(); humanLog/humanWarn arediff --git a/internal/eslint-plugin-astryx/no-raw-console-cli.test.mjs b/internal/eslint-plugin-astryx/no-raw-console-cli.test.mjsindex 1a62d40804..0e75e9ec48 100644--- a/internal/eslint-plugin-astryx/no-raw-console-cli.test.mjs+++ b/internal/eslint-plugin-astryx/no-raw-console-cli.test.mjs@@ -42,11 +42,16 @@ ruleTester.run('no-raw-console-cli', rule, {code: `console.log('banner');`,filename: '/repo/packages/cli/clients/cli/index.mjs',},- // Exempt: bin/astryx.mjs (entrypoint / error boundary)+ // Exempt: bin/astryx.mjs (entrypoint / Node gate){code: `console.log('raw');`,filename: '/repo/packages/cli/clients/cli/bin/astryx.mjs',},+ // Exempt: run.mjs (one run / error boundary)+ {+ code: `console.log('raw');`,+ filename: '/repo/packages/cli/clients/cli/run.mjs',+ },// Exemption is path-suffix based and tolerant of Windows separators{code: `console.log('raw');`,diff --git a/packages/cli/README.md b/packages/cli/README.mdindex c65bb73985..c61352759c 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -376,6 +376,35 @@ try {The CLI command handlers are thin wrappers around these functions: they parse args, call the API, then format the output (JSON or text). This guarantees that `@astryxdesign/cli/api` and `astryx --json` always return identical data.+### Host entry++A tool that carries this CLI and runs it for its own users starts it through `@astryxdesign/cli/host`, once per process. The run behaves as the `astryx` bin does with the same arguments in the same folder: it finds the project there, hands a project's run to the project's own CLI, and owns the process's working folder, arguments, standard streams, and exit.++```javascript+import {runHostedCli} from '@astryxdesign/cli/host';++const {status} = await runHostedCli({+ argv: process.argv.slice(2),+ cwd: process.cwd(),+ cliCommand: 'acme astryx',+});+process.exitCode = status;+```++| Option | Default | Meaning |+| -------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `argv` | none | The arguments after `astryx`. |+| `cwd` | the process's working folder | The folder the run works in. It must exist. |+| `cliCommand` | none (the package manager's name) | The command the tool's users type, such as `acme astryx`. Printed commands start with it unless the integrations the run loads declare their own `cliCommand`. A non-blank single line of at most 120 characters, with no surrounding spaces. |+| `declinedProjectCli` | none | When the tool found the project's own CLI and did not run it, why, in its own words, such as `untrusted`. The run is then never handed to that CLI: its release answers in its place when this copy or a package set's host entry is that release; otherwise this copy answers, with one warning line naming the reason. |+| `roots` | none | The tool's package sets, in its order of preference: folders whose `node_modules` each hold a CLI, the Core equal to it, and the integrations installed with them. A run never installs a release; when another release answers the folder, the first set whose CLI and Core are that release serves the run. |+| `integrations` | none | Integrations the tool approves for use outside a project, by package name, loaded from the package set that serves the run. |+| `discoverSources` | none | The tool's own discover sources, called after every integration's source and reported as the host's. Another package set's host entry that answers the run gets them too. |++It resolves with `{status, packages}`: the exit status the bin would exit with, and each package the run resolved with its version and whether it came from the project or a package set. When another package set's release answers through its own host entry, that entry runs in the same process with the same inputs, and the call resolves with its result. It rejects with a `TypeError` before anything runs for an unknown option or an invalid value, and with an `Error` before anything runs when a run already started in the process.++Like the bin, a run ends the process with its exit status, and the call never resolves, when it prints help or the version (`--help`, `-h`, `help`, `--version`, `-V`, `--version --json`), rejects the command line, reports an error it stops on (every error in `--json` mode included), meets an unexpected error, or hands the run to another CLI's bin: the project's own CLI when `declinedProjectCli` is absent, or a package set whose CLI ships no host entry. `astryx docs cli/host-entry` has the same guide.+### Consumer utilitiesIf you're spawning the CLI as a subprocess rather than importing the API directly:diff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjsindex 291958ab56..12b5156043 100644--- a/packages/cli/api/discover/_adapter.mjs+++ b/packages/cli/api/discover/_adapter.mjs@@ -25,6 +25,7 @@ import {availableComputerIntegrations,} from '../../foundation/config/project.mjs';import {isOutsideProject} from '../../foundation/env/project-scope.mjs';+import {hostedRun} from '../../foundation/runtime/package-root.mjs';import {scanAllPackages,findComponentInPackages,@@ -242,6 +243,7 @@ export async function describeInstalled(project, scanned) {* @returns {boolean}*/export function hasSources(project) {+ if (doorSources().length > 0) return true;if (project == null) return false;if (typeof project.config?.discover === 'function') return true;return project.loadedIntegrations.some(@@ -249,6 +251,19 @@ export function hasSources(project) {);}+/** Where a discover source a host passed comes from (spec AST-081 FR1). */+const DOOR_SOURCE = 'the host';++/**+ * The discover sources the host that started this run passed, if any.+ * @returns {readonly DiscoverSource[]}+ */+function doorSources() {+ return /** @type {readonly DiscoverSource[]} */ (+ hostedRun()?.discoverSources ?? []+ );+}+/** The source name of a package installed for the computer. */const COMPUTER_SOURCE = 'installed for this computer';@@ -479,7 +494,8 @@ export function defaultCacheDir() {/*** @param {string} cacheDir- * @param {string} from+ * @param {string} from the source's key: its `from` label, with the host for+ * a host's source* @param {{package?: string, version?: string}} request*/function savedCopyPath(cacheDir, from, request) {@@ -557,8 +573,9 @@ async function callSource(source, request, label, timeoutMs) {}/**- * Call the project's own discover sources — the project's `discover` first,- * then each integration's in load order — once per distinct function. A source that+ * Call the discover sources — the project's `discover` first, then each+ * integration's in load order, then each a host passed, named as the host's+ * (spec AST-081 FR1, AST-051 FR6) — once per distinct function. A source that* throws, times out, or returns an invalid catalog falls back to its saved copy;* with none, it is reported and adds nothing. The others always count.*@@ -572,20 +589,30 @@ async function callOwnSources(project, request = {}, options = {}) {const {cacheDir = defaultCacheDir(), timeoutMs = SOURCE_TIMEOUT_MS} = options;/** @type {CatalogResult} */const result = {sources: [], packages: []};- if (project == null) return result;+ const fromDoor = doorSources();+ if (project == null && fromDoor.length === 0) return result;- /** @type {Array<{from: string, source?: DiscoverSource, error?: string}>} */+ /** @type {Array<{from: string, key?: string, source?: DiscoverSource, error?: string}>} */const origins = [];- if (typeof project.config?.discover === 'function') {+ if (typeof project?.config?.discover === 'function') {origins.push({from: 'astryx.config', source: project.config.discover});}- for (const integration of project.loadedIntegrations) {+ for (const integration of project?.loadedIntegrations ?? []) {if (integration.__discoverError) {origins.push({from: integration.name, error: integration.__discoverError});} else if (integration.__discover) {origins.push({from: integration.name, source: integration.__discover});}}+ // Every tool that carries the CLI reports its sources as the host's, so+ // their saved copies are kept per host, by the root that holds its CLI+ // (spec:AST-051 FR8).+ const host = hostedRun()?.startingRoot ?? '';+ fromDoor.forEach((source, index) => {+ const from =+ fromDoor.length === 1 ? DOOR_SOURCE : `${DOOR_SOURCE} (${index + 1})`;+ origins.push({from, key: `${from}\n${host}`, source});+ });/** @type {Set<unknown>} */const called = new Set();@@ -594,7 +621,7 @@ async function callOwnSources(project, request = {}, options = {}) {const ask = request.package? {package: request.package, ...(request.version ? {version: request.version} : {})}: {};- for (const {from, source, error} of origins) {+ for (const {from, key = from, source, error} of origins) {if (source == null) {result.sources.push({name: from, from, status: 'failed', error});continue;@@ -603,7 +630,7 @@ async function callOwnSources(project, request = {}, options = {}) {called.add(source);const label = `the discover source from ${from}`;- const file = savedCopyPath(cacheDir, from, ask);+ const file = savedCopyPath(cacheDir, key, ask);/** @type {import('../../authoring/discover/type').DiscoverCatalog} */let catalog;try {diff --git a/packages/cli/api/discover/_adapter.test.mjs b/packages/cli/api/discover/_adapter.test.mjsindex fe927a7400..eb5e0cff36 100644--- a/packages/cli/api/discover/_adapter.test.mjs+++ b/packages/cli/api/discover/_adapter.test.mjs@@ -21,6 +21,10 @@ import {withDeclaredOfficial,} from './_adapter.mjs';import {parseDiscoverCatalog} from '../../authoring/discover/parse.mjs';+import {+ _resetHostedRun,+ activateHostedRun,+} from '../../foundation/runtime/package-root.mjs';/** No official packages, so a test sees only its own sources after it. */const NO_OFFICIAL = {packages: []};@@ -230,6 +234,44 @@ describe('callSources', () => {expect(otherRequest.sources[0].status).toBe('failed');});+ it("keeps a host's saved copies per host, so one tool never answers with another's", async () => {+ let online = true;+ const source = async () => {+ if (!online) throw new Error('offline');+ return catalog('Acme catalog', [pkg('@acme/one')]);+ };+ const options = {cacheDir, official: NO_OFFICIAL};+ try {+ activateHostedRun({+ discoverSources: [source],+ startingRoot: '/tools/acme',+ });+ await callSources(undefined, {}, options);+ online = false;+ const sameHost = await callSources(undefined, {}, options);+ expect(sameHost.sources[0]).toMatchObject({+ name: 'Acme catalog',+ from: 'the host',+ status: 'saved',+ });++ _resetHostedRun();+ activateHostedRun({+ discoverSources: [source],+ startingRoot: '/tools/other',+ });+ const otherHost = await callSources(undefined, {}, options);+ expect(otherHost.sources[0]).toMatchObject({+ from: 'the host',+ status: 'failed',+ error: 'offline',+ });+ expect(otherHost.packages).toEqual([]);+ } finally {+ _resetHostedRun();+ }+ });+it('keeps the saved copy in the cache directory, not in the project', async () => {await callSources(project({diff --git a/packages/cli/api/docs/docs.test.mjs b/packages/cli/api/docs/docs.test.mjsindex fdbd8cdc73..a4bb180548 100644--- a/packages/cli/api/docs/docs.test.mjs+++ b/packages/cli/api/docs/docs.test.mjs@@ -123,7 +123,13 @@ describe('docs() dispatcher routing', () => {kind: 'namespace',package: '@astryxdesign/cli',breadcrumb: [{route: 'cli', title: 'Astryx CLI'}],- content: [],+ // Its one block points to the host entry's guide.+ content: [+ {+ type: 'prose',+ text: expect.stringContaining('`astryx docs cli/host-entry`'),+ },+ ],});expect(r.data.slots.flatMap(slot => slot.children.map(c => c.route))).toEqual(['cli/api/functions',diff --git a/packages/cli/assets/docs/tree/api.doc.mjs b/packages/cli/assets/docs/tree/api.doc.mjsindex 2fc3f39e72..34e7718360 100644--- a/packages/cli/assets/docs/tree/api.doc.mjs+++ b/packages/cli/assets/docs/tree/api.doc.mjs@@ -20,6 +20,12 @@ export const docs = {slots: {kinds: {title: 'Reference', accepts: {kinds: ['namespace']}},},+ blocks: [+ {+ type: 'prose',+ text: 'To run the whole CLI from your own command-line tool, with its arguments, folder, and command name, use the host entry: {@link generic:host-entry}.',+ },+ ],adopts: [{source: {group: 'cli/api', kinds: ['function', 'schema', 'enum']},diff --git a/packages/cli/assets/docs/tree/host-entry.doc.mjs b/packages/cli/assets/docs/tree/host-entry.doc.mjsnew file mode 100644index 0000000000..d507c2148c--- /dev/null+++ b/packages/cli/assets/docs/tree/host-entry.doc.mjs@@ -0,0 +1,128 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/host-entry`: run the CLI from a tool that carries it,+ * through `@astryxdesign/cli/host` (spec AST-081 FR1,+ * architecture:cli-surface INV30).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'host-entry',+ placement: {parent: 'namespace:cli', slot: 'guides', order: 15},+ title: 'Host entry',+ category: 'guide',+ keywords: [+ 'host entry',+ 'runHostedCli',+ '@astryxdesign/cli/host',+ 'carry the cli',+ 'embed the cli',+ 'programmatic run',+ 'package sets',+ 'cliCommand',+ ],+ description:+ 'Run the Astryx CLI from your own command-line tool: the inputs `runHostedCli` takes, what it returns, and when the process ends instead.',+ sections: [+ {+ id: 'start',+ title: 'Start a run',+ content: [+ {+ type: 'prose',+ text: "A tool that carries the CLI for its own users starts one run per process with `runHostedCli` from `@astryxdesign/cli/host`. The run behaves as the CLI's own command does with the same arguments in the same folder, and the commands it prints start with your tool's command.",+ },+ {+ type: 'code',+ lang: 'javascript',+ code: "import {runHostedCli} from '@astryxdesign/cli/host';\n\nconst {status} = await runHostedCli({\n argv: process.argv.slice(2),\n cwd: process.cwd(),\n cliCommand: 'acme astryx',\n});\nprocess.exitCode = status;",+ },+ ],+ },+ {+ id: 'options',+ title: 'Options',+ content: [+ {+ type: 'table',+ headers: ['Option', 'Default', 'Meaning'],+ rows: [+ [+ '`argv`',+ 'none',+ 'The command-line arguments, without the command name.',+ ],+ [+ '`cwd`',+ "the process's working folder",+ 'The folder the run works in. It must exist.',+ ],+ [+ '`cliCommand`',+ "the package manager's name",+ 'The command your users type, such as `acme astryx`: a non-blank single line of at most 120 characters, with no surrounding spaces.',+ ],+ [+ '`declinedProjectCli`',+ 'none',+ "Why you did not run the project's own CLI, such as `untrusted`: a non-blank single line of at most 120 characters. That CLI then never runs.",+ ],+ [+ '`roots`',+ 'none',+ 'Your package sets, in order of preference: folders whose `node_modules` each hold a CLI, the Core of the same release, and integrations. A run never installs a release; it takes the release a project needs from the first set that holds it.',+ ],+ [+ '`integrations`',+ 'none',+ 'Integrations you approve for use outside a project, by package name.',+ ],+ [+ '`discoverSources`',+ 'none',+ "Your own discover sources. `astryx discover` reports each as the host's.",+ ],+ ],+ },+ ],+ },+ {+ id: 'result',+ title: 'Result and errors',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "It resolves with `{status, packages}`: the exit status the CLI's own command would exit with, and each package the run used, with its version and whether it came from the project or a package set.",+ 'When another release answers from one of your package sets through its own host entry, that entry runs in the same process with the same inputs, and the call resolves with its result.',+ 'It rejects with a `TypeError`, before anything runs, for an unknown option or an invalid value, and with an `Error` when a run already started in the process. Start each run in a new process.',+ ],+ },+ ],+ },+ {+ id: 'process-ends',+ title: 'When the process ends instead',+ content: [+ {+ type: 'prose',+ text: "Like the CLI's own command, a run ends the process with its exit status, and the call never resolves, when it:",+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'prints help or the version (`--help`, `-h`, `help`, `--version`, `-V`, `--version --json`);',+ 'rejects the command line, such as an unknown command or option;',+ 'reports an error it stops on, including every error in `--json` mode;',+ 'meets an unexpected error;',+ "hands the run to another CLI's own command: the project's CLI when you pass no `declinedProjectCli`, or a package set whose CLI has no host entry.",+ ],+ },+ ],+ },+ ],+};diff --git a/packages/cli/clients/cli/bin/astryx.mjs b/packages/cli/clients/cli/bin/astryx.mjsindex 90afe4fabb..fabdf97078 100755--- a/packages/cli/clients/cli/bin/astryx.mjs+++ b/packages/cli/clients/cli/bin/astryx.mjs@@ -53,84 +53,13 @@ if (!isNodeVersionSupported(process.versions.node)) {process.exit(1);}-// Global mode: choose the release that answers this folder and, when it is-// not this copy, hand the run to it before anything the project provides (its-// astryx.config, integrations, or Core) is loaded. Returns only when this copy-// answers. See foundation/release/handoff.mjs and spec AST-081 FR2 and FR9.-const {startRun} = await importSrc('../../foundation/release/handoff.mjs');-await startRun({+// Global mode: the run chooses the release that answers this folder and, when+// it is not this copy, hands the run to it before anything the project+// provides (its astryx.config, integrations, or Core) is loaded; only then+// does it load and dispatch the command. See clients/cli/run.mjs,+// foundation/release/handoff.mjs, and spec AST-081 FR2 and FR9.+const {runCli} = await importSrc('run.mjs');+await runCli({cliRoot: join(binDir, '..', '..', '..'),argv: process.argv.slice(2),});--// Imports that transitively load `styleText` must happen AFTER the gate above,-// so they are dynamically imported here rather than at the top of the module.-const {- program,- loadProjectDebugHandler,- loadProjectForHelp,- handleVersionJsonPreflight,-} = await importSrc('index.mjs');-const {isJsonMode, toErrorEnvelope} = await importSrc('../../foundation/response/json.mjs');-const {handleCommanderError} = await importSrc('lib/json-shim.mjs');-const {setOutcome} = await importSrc('../../foundation/debug/index.mjs');--/**- * Top-level error boundary (contract guarantee #4): an uncaught throw must- * never reach a --json consumer as a raw stack trace. If we're in JSON mode,- * convert it to the contract's error envelope on stdout and exit 1; otherwise- * preserve the normal human-facing behavior.- *- * We detect JSON mode two ways: the global flag (set once root options are- * parsed) and a raw argv check, since a throw can occur during parsing/command- * load — before the preAction hook engages the flag.- */-function inJsonMode() {- return isJsonMode() || process.argv.slice(2).includes('--json');-}--/** @param {unknown} err */-function handleFatal(err) {- // CommanderError (parse errors, --help, unknown command) routes- // through the JSON shim so that a --json consumer always gets a- // valid envelope and the right exit code. handleCommanderError- // calls process.exit when it owns the error.- if (handleCommanderError(err)) return;-- // Anything still here is an uncaught throw or an unhandled rejection —- // a bug rather than a user error, and the class of failure most worth- // having a record of.- setOutcome('fatal', {exitCode: 1, error: err});-- if (inJsonMode()) {- // Only emit if a command didn't already produce an envelope.- if (!process.__xdsJsonHandled) {- process.__xdsJsonHandled = true;- console.log(JSON.stringify(toErrorEnvelope(err), null, 2));- }- process.exit(1);- }- // Human mode: preserve Commander/Node default-ish behavior.- console.error(err instanceof Error ? err.stack || err.message : String(err));- process.exit(1);-}--process.on('unhandledRejection', handleFatal);-process.on('uncaughtException', handleFatal);--// Pick up the project's `debug` function before parsing, so parse errors and-// `--help` — which short-circuit before any hook runs — are reported too.-await loadProjectDebugHandler();-// Help prints its commands while Commander parses, so a help run reads the-// project's declared `cliCommand` here.-await loadProjectForHelp();--// `--version --json` answers and exits without Commander, so it runs here —-// after the handler exists, or the run would go unrecorded.-handleVersionJsonPreflight();--try {- await program.parseAsync(process.argv);-} catch (err) {- handleFatal(err);-}diff --git a/packages/cli/clients/cli/run.mjs b/packages/cli/clients/cli/run.mjsnew file mode 100644index 0000000000..550ee27317--- /dev/null+++ b/packages/cli/clients/cli/run.mjs@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file One run of the CLI, after the Node version gate: choose who answers+ * the folder, hand the run off when that is another release (spec AST-081+ * FR2, FR9), then dispatch the command.+ *+ * @input The arguments after `astryx`, read from `process.argv`; the CLI+ * package root; and, for a run a programmatic host started, the reason the+ * host declined the project's own CLI.+ * @output The command's effects. The run owns the process: its exit status is+ * `process.exitCode`, unless a hand-off or a failure exits the process.+ * @position clients/cli — called by `bin/astryx.mjs` and by the host entry+ * (`host/index.mjs`).+ */++/**+ * Run the CLI once in this process.+ *+ * Every import here is dynamic: modules that load `styleText` must load only+ * after the bin's Node version gate, and the release choice must run before+ * the command modules load, so a run handed to another release loads none of+ * them.+ *+ * @param {{cliRoot: string, argv: string[], declinedProjectCli?: string}} input+ * @returns {Promise<import('../../host/index.js').HostedCliResult | undefined>}+ * resolves when the command has finished; with another release's result+ * when, in a hosted run, that release's host entry answered+ */+export async function runCli({cliRoot, argv, declinedProjectCli}) {+ const {startRun} = await import('../../foundation/release/handoff.mjs');+ const answered = await startRun({cliRoot, argv, declinedProjectCli});+ if (answered) return answered;++ const {+ program,+ loadProjectDebugHandler,+ loadProjectForHelp,+ handleVersionJsonPreflight,+ } = await import('./index.mjs');+ const {isJsonMode, toErrorEnvelope} =+ await import('../../foundation/response/json.mjs');+ const {handleCommanderError} = await import('./lib/json-shim.mjs');+ const {setOutcome} = await import('../../foundation/debug/index.mjs');++ /**+ * Top-level error boundary (contract guarantee #4): an uncaught throw must+ * never reach a --json consumer as a raw stack trace. If we're in JSON mode,+ * convert it to the contract's error envelope on stdout and exit 1;+ * otherwise preserve the normal human-facing behavior.+ *+ * We detect JSON mode two ways: the global flag (set once root options are+ * parsed) and a raw argv check, since a throw can occur during+ * parsing/command load — before the preAction hook engages the flag.+ */+ function inJsonMode() {+ return isJsonMode() || process.argv.slice(2).includes('--json');+ }++ /** @param {unknown} err */+ function handleFatal(err) {+ // CommanderError (parse errors, --help, unknown command) routes+ // through the JSON shim so that a --json consumer always gets a+ // valid envelope and the right exit code. handleCommanderError+ // calls process.exit when it owns the error.+ if (handleCommanderError(err)) return;++ // Anything still here is an uncaught throw or an unhandled rejection —+ // a bug rather than a user error, and the class of failure most worth+ // having a record of.+ setOutcome('fatal', {exitCode: 1, error: err});++ if (inJsonMode()) {+ // Only emit if a command didn't already produce an envelope.+ if (!process.__xdsJsonHandled) {+ process.__xdsJsonHandled = true;+ console.log(JSON.stringify(toErrorEnvelope(err), null, 2));+ }+ process.exit(1);+ }+ // Human mode: preserve Commander/Node default-ish behavior.+ console.error(+ err instanceof Error ? err.stack || err.message : String(err),+ );+ process.exit(1);+ }++ process.on('unhandledRejection', handleFatal);+ process.on('uncaughtException', handleFatal);++ // Pick up the project's `debug` function before parsing, so parse errors+ // and `--help` — which short-circuit before any hook runs — are reported+ // too.+ await loadProjectDebugHandler();+ // Help prints its commands while Commander parses, so a help run reads the+ // project's declared `cliCommand` here.+ await loadProjectForHelp();++ // `--version --json` answers and exits without Commander, so it runs here —+ // after the handler exists, or the run would go unrecorded.+ handleVersionJsonPreflight();++ try {+ await program.parseAsync(process.argv);+ } catch (err) {+ handleFatal(err);+ }+}diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex b7da2188e9..7aa69b4331 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -89,6 +89,10 @@ import {} from '../../assets/codemods/integration-discovery.mjs';import {validateLoadedIntegration} from '../integrations/validate-contributions.mjs';import {recordDeclaredCliCommands} from '../env/cli-command.mjs';+import {+ hostedRun,+ recordResolvedIntegrations,+} from '../runtime/package-root.mjs';import {InMemoryConfigCache,cacheKey,@@ -121,9 +125,16 @@ function errorMessage(err) {*/export function computerIntegrationCandidates(cwd = process.cwd()) {try {- const cliRoot = isOutsideProject(cwd) ? CLI_ROOT : globalCliRoot(cwd);+ const outside = isOutsideProject(cwd);+ const cliRoot = outside ? CLI_ROOT : globalCliRoot(cwd);return cliRoot- ? scanComputerIntegrations({cliRoot, release: cliVersion()})+ ? scanComputerIntegrations({+ cliRoot,+ release: cliVersion(),+ // Outside a project, the integrations a host approves load from the+ // package set that serves the run too (cli-surface INV30).+ approved: outside ? (hostedRun()?.integrations ?? []) : [],+ }): [];} catch {return [];@@ -580,6 +591,8 @@ export class Project {: []),]);loadedIntegrations = resolution.integrations;+ // A hosted run returns each package it resolved (cli-surface INV30).+ recordResolvedIntegrations(loadedIntegrations);// The picker (getCliInvocation) is synchronous, so the commands these// integrations declare are recorded here, where they become known.recordDeclaredCliCommands(projectDir, loadedIntegrations);diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex 0db4192e23..29c9df7c84 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -339,6 +339,10 @@ const RUNNERS = {runs: "the CLI release that answers a project's run, when it is not this copy",sites: ['child_process.spawn'],},+ 'host/index.mjs': {+ runs: "another release's host entry, from one of the host's package sets, when that release answers a hosted run",+ sites: ['import(<computed>)'],+ },'scripts/generate-cli-readme.mjs': {runs: '`astryx manifest` and the error-code and response-type docs, to write the README tables (build time, not shipped)',sites: ['child_process.spawnSync', 'import(<computed>)'],diff --git a/packages/cli/foundation/fs/paths.mjs b/packages/cli/foundation/fs/paths.mjsindex 8c99105b03..fbd6b3ef3f 100644--- a/packages/cli/foundation/fs/paths.mjs+++ b/packages/cli/foundation/fs/paths.mjs@@ -14,6 +14,7 @@ import {listDir, pathExists} from './listing-cache.mjs';import {ERROR_CODES} from '../response/error-codes.mjs';import {carriedCore, runChoice} from '../release/run-context.mjs';import {findDeclaringPackage} from '../release/project.mjs';+import {hostedRun, recordResolved} from '../runtime/package-root.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -35,7 +36,33 @@ export const CLI_ROOT = path.resolve(__dirname, '..', '..');* @returns {string | null}*/export function findCoreDir(startDir = process.cwd()) {- return findProjectCoreDir(startDir) ?? carriedCoreFor(startDir).dir;+ const own = findProjectCoreDir(startDir);+ return own+ ? noteCore(own, 'project')+ : noteCore(carriedCoreFor(startDir).dir);+}++/**+ * Note the Core a hosted run reads, for the record its host entry returns+ * (architecture:cli-surface INV30). Does nothing outside a hosted run.+ * @template {string | null} T+ * @param {T} dir+ * @param {'project'} [source] where it came from, when the caller knows+ * @returns {T}+ */+function noteCore(dir, source) {+ if (dir && hostedRun()) {+ let version;+ try {+ version = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ ).version;+ } catch {+ version = null;+ }+ recordResolved('@astryxdesign/core', version, dir, source);+ }+ return dir;}/**@@ -67,14 +94,14 @@ export function unavailableCoreMessage(found, inProject) {*/export function requireCoreDir(startDir = process.cwd()) {const found = findProjectCoreDir(startDir) ?? carriedCoreFor(startDir, true);- if (typeof found === 'string') return found;+ if (typeof found === 'string') return noteCore(found, 'project');if (found.unavailable) {throw codedError(unavailableCoreMessage(found, runChoice(startDir).inProject),ERROR_CODES.ERR_VERSIONS_UNAVAILABLE,);}- if (found.dir) return found.dir;+ if (found.dir) return noteCore(found.dir);throw codedError('Could not find @astryxdesign/core package',ERROR_CODES.ERR_CORE_NOT_FOUND,diff --git a/packages/cli/foundation/integrations/computer-integrations.mjs b/packages/cli/foundation/integrations/computer-integrations.mjsindex d714f07110..603c0062c1 100644--- a/packages/cli/foundation/integrations/computer-integrations.mjs+++ b/packages/cli/foundation/integrations/computer-integrations.mjs@@ -225,12 +225,19 @@ export function peerProblem(pkg, release) {/*** The computer-level integrations installed beside the CLI at `cliRoot`, in- * name order (declaration order when the root declares them). Reads+ * name order (declaration order when the root declares them), then each+ * integration a host approves (`approved`, architecture:cli-surface INV30),+ * resolved by name from the package set that holds that CLI alone. Reads* package.json files only.- * @param {{cliRoot: string, release: string, cacheDir?: string}} options+ * @param {{cliRoot: string, release: string, cacheDir?: string, approved?: readonly string[]}} options* @returns {ComputerIntegrationCandidate[]}*/-export function scanComputerIntegrations({cliRoot, release, cacheDir}) {+export function scanComputerIntegrations({+ cliRoot,+ release,+ cacheDir,+ approved = [],+}) {const self = real(cliRoot);/** @type {ComputerIntegrationCandidate[]} */const found = [];@@ -238,21 +245,43 @@ export function scanComputerIntegrations({cliRoot, release, cacheDir}) {for (const root of computerInstallRoots(cliRoot, {cacheDir})) {scanRoot(root, {self, release, found, seen});}+ const owner = approved.length > 0 ? installPlaceOf(self).owner : null;+ if (owner) scanRoot(owner, {self, release, found, seen}, approved);return found;}/**- * Add the integrations installed in one install root.+ * `name` as installed in `root`'s own `node_modules`, never in a folder above.+ * @param {string} name+ * @param {string} root+ * @returns {{packageDir: string, hostDir: string} | null}+ */+function ownPackageDir(name, root) {+ const packageDir = path.join(root, 'node_modules', ...name.split('/'));+ return fs.existsSync(path.join(packageDir, 'package.json'))+ ? {packageDir, hostDir: root}+ : null;+}++/**+ * Add the integrations installed in one install root: those it declares or+ * installs, or, given `approved`, those names installed in its own+ * `node_modules`.* @param {string} root* @param {{self: string, release: string, found: ComputerIntegrationCandidate[], seen: Set<string>}} into+ * @param {readonly string[] | null} [approved]*/-function scanRoot(root, {self, release, found, seen}) {- const declared = readPackage(root)- ? readDeclaredDependencies(root).map(d => d.name)- : installedNames(root);+function scanRoot(root, {self, release, found, seen}, approved = null) {+ const declared =+ approved ??+ (readPackage(root)+ ? readDeclaredDependencies(root).map(d => d.name)+ : installedNames(root));for (const name of declared) {if (NOT_INTEGRATIONS.has(name)) continue;- const resolved = resolveInstalledPackageDir(name, root);+ const resolved = approved+ ? ownPackageDir(name, root)+ : resolveInstalledPackageDir(name, root);if (!resolved) continue;const identity = real(resolved.packageDir);if (identity === self || seen.has(identity)) continue;diff --git a/packages/cli/foundation/release/handoff.mjs b/packages/cli/foundation/release/handoff.mjsindex d4c975a45e..af16e01416 100644--- a/packages/cli/foundation/release/handoff.mjs+++ b/packages/cli/foundation/release/handoff.mjs@@ -19,9 +19,26 @@* (notices.mjs); a global copy also starts the daily update check, which* installs nothing (global-state.mjs).*- * @input the running copy, argv, the working folder- * @output returns when this copy answers; otherwise never returns- * @position foundation/release — called once by clients/cli/bin/astryx.mjs.+ * A programmatic host that found the project's own CLI and did not run it+ * passes the reason (spec AST-081 FR1, FR2). That run is never handed to the+ * project's CLI: this copy answers in its place when it is that CLI's release,+ * saying so in a line of its own; a package set of the host's whose CLI is+ * that release answers through its own host entry; and otherwise this copy+ * answers as for a release that cannot be obtained, with the warning naming+ * the reason.+ *+ * A hosted run installs nothing (architecture:cli-surface INV30): a release+ * other than this copy comes only from the first of the host's package sets+ * that qualifies. When that CLI ships a host entry, the entry runs in this+ * process with the same inputs, discover sources included, and the host's+ * call settles with its result; otherwise its bin takes the run. With no such+ * set, this copy answers, announced.+ *+ * @input the running copy, argv, the working folder, and a host's+ * declined-project-CLI reason+ * @output returns when this copy answers, or with another release's result+ * when its host entry answered; never returns after a hand-off to a bin+ * @position foundation/release — called once per run by clients/cli/run.mjs.*/import {spawn} from 'node:child_process';@@ -32,8 +49,10 @@ import {isGlobalCopy,namesWhoAnswered,packageRootOf,+ projectRootOf,runningCopy,} from './choose.mjs';+import {readReleaseFacts} from './project.mjs';import {ensureRelease, userCacheDir} from './cache.mjs';import {maybeFetchCore,@@ -43,6 +62,8 @@ import {import {recordRunChoice} from './run-context.mjs';import {noticeLines} from './notices.mjs';import {cliDoor, runWithCliDoor} from '../env/cli-command.mjs';+import {hostedRun} from '../runtime/package-root.mjs';+import {qualifyingRoot} from '../runtime/package-set.mjs';/** Where each release's notes are published. */@@ -63,6 +84,17 @@ export function whoAnsweredLine(choice, computer = false) {: `astryx: answered by CLI ${choice.version} with Core ${core}, outside a project`;}+/**+ * The line for a run this copy answers in place of the project's own CLI,+ * which a host declined, when this copy is that CLI's release (FR2).+ * @param {string} version+ * @param {string} reason the reason, as {@link declinedReasonText} words it+ * @returns {string}+ */+export function inPlaceOfProjectLine(version, reason) {+ return `astryx: answered by CLI ${version}, the release of this project's CLI, in its place (${reason})`;+}+/*** The line for a run handed to the project's own CLI.* @param {string} projectVersion@@ -131,16 +163,32 @@ function failUnavailable(message, json) {process.exit(1);}+/**+ * The fallback warning's reason for a project CLI a host declined.+ * @param {string} reason the host's own words+ * @returns {string}+ */+export function declinedReasonText(reason) {+ return `project CLI skipped: ${reason}`;+}+/*** Choose who answers and hand off when it is not this copy.- * @param {{cliRoot: string, argv: string[]}} input argv after `node astryx`- * @returns {Promise<void>} resolves when this copy answers+ * @param {{cliRoot: string, argv: string[], declinedProjectCli?: string}} input+ * argv after `node astryx`; the reason a programmatic host declined the+ * project's own CLI, when it did+ * @returns {Promise<import('../../host/index.js').HostedCliResult | undefined>}+ * resolves with nothing when this copy answers, and with that release's+ * result when another package set's host entry answered a hosted run*/-export async function startRun({cliRoot, argv}) {+export async function startRun({cliRoot, argv, declinedProjectCli}) {const json = argv.includes('--json');const self = runningCopy(cliRoot);const cacheDir = userCacheDir();- const global = isGlobalCopy(cliRoot, cacheDir);+ // A host carries its own CLI and keeps it current itself: a hosted copy+ // runs none of the global copy's background work, and installs nothing.+ const hosted = hostedRun();+ const global = !hosted && isGlobalCopy(cliRoot, cacheDir);if (global) {try {maybeStartCheck();@@ -189,7 +237,46 @@ export async function startRun({cliRoot, argv}) {};}- if (choice.unavailable && choice.copy === 'project') {+ // A host declined the project's own CLI (FR2): the run is never handed to+ // it. The release equal to that CLI's version answers in its place when+ // this copy is that release, or when a package set of the host's holds it+ // with a host entry; otherwise this copy answers, announced as for a release+ // that cannot be obtained, naming the reason.+ let declined = null;+ /** Set when this copy answers in place of the declined CLI, its release. */+ let inPlace = null;+ if (+ declinedProjectCli &&+ choice.copy === 'project' &&+ choice.answer !== 'self'+ ) {+ if (choice.version === self.version) {+ // Still the project CLI's release (`copy` stays `project`), never the+ // release matched to the project's Core, which can be another.+ choice = {...choice, answer: 'self', bin: null, unavailable: null};+ inPlace = declinedReasonText(declinedProjectCli);+ } else {+ const served = hosted+ ? qualifyingRoot({+ release: choice.version,+ projectDir: projectDirOf(process.cwd()),+ roots: hosted.roots,+ needsHostEntry: true,+ })+ : null;+ if (served && 'root' in served && served.hostEntry) {+ const answered = await answerInPackageSet(+ served.hostEntry,+ served.root,+ {argv, declinedProjectCli},+ );+ if (answered) return answered;+ }+ declined = declinedReasonText(declinedProjectCli);+ }+ }++ if (!declined && choice.unavailable && choice.copy === 'project') {failUnavailable(`This project's CLI ${choice.version} could not be started: ${choice.unavailable}. Reinstall the project's dependencies.`,json,@@ -245,6 +332,11 @@ export async function startRun({cliRoot, argv}) {});};+ if (declined) {+ await fallBack(declined);+ return;+ }+if (choice.unavailable) {await fallBack(choice.unavailable);return;@@ -256,6 +348,8 @@ export async function startRun({cliRoot, argv}) {// line; a hint after the command, once a day, says how to match it.if (!json && (choice.copy === 'matched' || choice.copy === 'carried'))console.error(whoAnsweredLine(choice, computer));+ else if (!json && inPlace)+ console.error(inPlaceOfProjectLine(choice.version, inPlace));process.once('exit', code => {if (code === 0) notify();});@@ -263,6 +357,32 @@ export async function startRun({cliRoot, argv}) {}let bin = choice.bin;+ if (!bin && hosted) {+ const served = qualifyingRoot({+ release: choice.version,+ projectDir: projectDirOf(process.cwd()),+ roots: hosted.roots,+ });+ if (!('root' in served)) {+ await fallBack(served.reason);+ return;+ }+ if (served.hostEntry) {+ const answered = await answerInPackageSet(served.hostEntry, served.root, {+ argv,+ });+ if (answered) return answered;+ }+ // A hosted run installs nothing (INV30): a set whose CLI starts through+ // neither its host entry nor a bin leaves this copy to answer.+ if (!served.bin) {+ await fallBack(+ `the CLI ${choice.version} in the package set at ${served.root} could not be started`,+ );+ return;+ }+ bin = served.bin;+ }if (!bin) {const release = ensureRelease(choice.version, {cacheDir,@@ -295,6 +415,53 @@ export async function startRun({cliRoot, argv}) {*/export const INTERRUPT_GRACE_MS = 5000;+/**+ * The project folder a run in `cwd` belongs to, or null outside a project.+ * @param {string} cwd+ * @returns {string | null}+ */+function projectDirOf(cwd) {+ try {+ return projectRootOf(readReleaseFacts(cwd));+ } catch {+ return null;+ }+}++/**+ * Hand a hosted run over to the CLI of one of the host's package sets,+ * through that CLI's own host entry, in this process, with the inputs this run+ * got: the arguments, the folder, the command name, the approved integrations,+ * the discover sources, and the reason the host declined the project's CLI.+ * Its roots are that package set alone. That CLI prints its own who-answered+ * line and notices, and the host's call settles with its result.+ * @param {string} hostEntry the package set's `host/index.mjs`+ * @param {string} root the package set+ * @param {{argv: string[], declinedProjectCli?: string}} run+ * @returns {Promise<import('../../host/index.js').HostedCliResult | null>} null+ * when the entry cannot be loaded, before anything ran+ */+async function answerInPackageSet(hostEntry, root, {argv, declinedProjectCli}) {+ const hosted = hostedRun();+ if (!hosted?.loadHostEntry) return null;+ let answer;+ try {+ answer = await hosted.loadHostEntry(hostEntry);+ } catch {+ return null;+ }+ const door = cliDoor();+ return answer({+ argv,+ cwd: process.cwd(),+ roots: [root],+ integrations: [...hosted.integrations],+ discoverSources: [...hosted.discoverSources],+ ...(door ? {cliCommand: door} : {}),+ ...(declinedProjectCli ? {declinedProjectCli} : {}),+ });+}+/*** Run `bin` as this run and end with its exit status.* @param {string} bindiff --git a/packages/cli/foundation/release/run-context.mjs b/packages/cli/foundation/release/run-context.mjsindex ee2ea25918..f164c3ce3c 100644--- a/packages/cli/foundation/release/run-context.mjs+++ b/packages/cli/foundation/release/run-context.mjs@@ -22,6 +22,7 @@ import {progressLine} from './handoff.mjs';import {isJsonMode} from '../response/json.mjs';import {cachedRelease, ensureRelease, userCacheDir} from './cache.mjs';import {readJson, findReadCore, CORE_PACKAGE_NAME} from './project.mjs';+import {hostedRun} from '../runtime/package-root.mjs';/** The running CLI package's folder. */const CLI_ROOT = path.resolve(@@ -105,6 +106,19 @@ export function carriedCore(options = {}) {if (besidePkg?.name === CORE_PACKAGE_NAME && besidePkg.version === version) {return {dir: beside, unavailable: null};}+ // A hosted run resolves from its package set alone and installs nothing+ // (architecture:cli-surface INV30): the Core beside the CLI, or none.+ if (hostedRun()) {+ if (!fetch) return {dir: null, unavailable: null};+ const reason =+ "a hosted run installs nothing, and the host's package set holds no Core beside its CLI";+ return {+ dir: null,+ unavailable: `Core ${version} could not be found: ${reason}`,+ version,+ reason,+ };+ }const cached = cachedRelease(version, cacheDir);if (cached) return {dir: cached.coreDir, unavailable: null};if (!fetch) return {dir: null, unavailable: null};diff --git a/packages/cli/foundation/runtime/hosted-runtime.test.mjs b/packages/cli/foundation/runtime/hosted-runtime.test.mjsnew file mode 100644index 0000000000..3a982c2fe5--- /dev/null+++ b/packages/cli/foundation/runtime/hosted-runtime.test.mjs@@ -0,0 +1,403 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A hosted run end to end, through `@astryxdesign/cli/host` in a host+ * process (architecture:cli-surface INV30, spec AST-081 FR1, FR2, FR9): a+ * release other than this copy comes from the first package set that+ * qualifies (another release's host entry runs in this process with the same+ * inputs, discover sources included, and the call settles with its result), a+ * hosted run installs nothing, a declined project CLI never runs, the host's+ * discover sources are called and named as the host's, and the result names+ * each package the run resolved and where it came from.+ */++import {describe, it, expect, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {+ cleanupFixtures,+ installCore,+ installStandInCli,+ project,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++const HOST = fileURLToPath(new URL('../../host/index.mjs', import.meta.url));+const SELF_VERSION = JSON.parse(+ fs.readFileSync(+ fileURLToPath(new URL('../../package.json', import.meta.url)),+ 'utf-8',+ ),+).version;++afterEach(cleanupFixtures);++/** JavaScript for a host's `discoverSources`: one source with one package. */+const ACME_SOURCE = `[async () => ({+ schemaVersion: 1,+ source: {name: 'Acme catalog', generatedAt: '2026-10-20T00:00:00.000Z', complete: true},+ packages: [{+ package: 'acme-widgets',+ integration: 'acme-widgets',+ aliases: [],+ latest: '1.0.0',+ versions: [{version: '1.0.0', publishedAt: null, prerelease: false, status: 'ok'}],+ contributions: [{kind: 'component', name: 'AcmeWidget'}],+ }],+})]`;++/**+ * Start a host process that calls `runHostedCli` once and writes what it+ * returned to a file.+ * @param {Record<string, unknown>} options JSON-safe options+ * @param {{sources?: string}} [extra] JavaScript for a `discoverSources` array+ */+function host(options, extra = {}) {+ const home = tempDir('home');+ const cache = tempDir('cache');+ const out = path.join(tempDir('out'), 'result.json');+ const script = `+const {runHostedCli} = await import(${JSON.stringify(HOST)});+const options = ${JSON.stringify(options)};+${extra.sources ? `options.discoverSources = ${extra.sources};` : ''}+const result = await runHostedCli(options);+(await import('node:fs')).writeFileSync(${JSON.stringify(out)}, JSON.stringify(result));+process.exitCode = result.status;+`;+ const run = spawnSync(+ process.execPath,+ ['--input-type=module', '-e', script],+ {+ cwd: tempDir('host-cwd'),+ encoding: 'utf-8',+ env: {+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ ([key]) => !/^(?:npm_|CI$|NO_UPDATE_NOTIFIER$)/iu.test(key),+ ),+ ),+ HOME: home,+ USERPROFILE: home,+ XDG_CACHE_HOME: cache,+ LOCALAPPDATA: cache,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ APPDATA: path.join(home, 'AppData', 'Roaming'),+ NO_COLOR: '1',+ npm_config_registry: 'http://127.0.0.1:9',+ },+ timeout: 60_000,+ },+ );+ return {+ status: run.status,+ stdout: run.stdout,+ stderr: run.stderr,+ cache,+ /** @returns {any} what runHostedCli returned, when it returned */+ result: () =>+ fs.existsSync(out) ? JSON.parse(fs.readFileSync(out, 'utf-8')) : null,+ /** @returns {any} the last stdout line, parsed */+ report: () => JSON.parse(run.stdout.trim().split('\n').pop() ?? 'null'),+ };+}++/**+ * A package set holding a stand-in CLI and a Core of `version`; with+ * `hostEntry`, the CLI ships a stand-in host entry that reports its options,+ * with the name of the catalog each discover source returns, and settles with+ * a record of its own.+ * @param {string} version+ * @param {{hostEntry?: boolean}} [options]+ */+function packageSet(version, options = {}) {+ const root = tempDir('set');+ const cli = installStandInCli(root, version, {bin: options.bin ?? true});+ installCore(root, version);+ if (options.hostEntry === 'broken') {+ // A host entry that loads but offers no runHostedCli.+ fs.mkdirSync(path.join(cli, 'host'), {recursive: true});+ fs.writeFileSync(path.join(cli, 'host', 'index.mjs'), 'export {};\n');+ } else if (options.hostEntry) {+ fs.mkdirSync(path.join(cli, 'host'), {recursive: true});+ fs.writeFileSync(+ path.join(cli, 'host', 'index.mjs'),+ `export async function runHostedCli({discoverSources = [], ...options}) {+ const catalogs = await Promise.all(discoverSources.map(source => source({})));+ console.log(JSON.stringify({+ hostEntry: ${JSON.stringify(version)},+ options,+ discoverSources: catalogs.map(catalog => catalog.source.name),+ }));+ return {+ status: 0,+ packages: [{name: '@astryxdesign/cli', version: ${JSON.stringify(version)}, source: 'package-set'}],+ };+}+`,+ );+ }+ return root;+}++/** Whether the run installed any release into the per-user cache. */+function installedARelease(cache) {+ return fs.existsSync(path.join(cache, 'astryx', 'releases'));+}++describe('a project whose own CLI cannot start, in a hosted run', () => {+ /** A project on Core 0.7.0 whose CLI 0.6.8 has no command. */+ function brokenProject() {+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ installCore(root, '0.7.0');+ installStandInCli(root, '0.6.8', {bin: false});+ return root;+ }++ it("is answered from the first package set whose CLI and Core match the project's Core", () => {+ const root = brokenProject();+ const run = host({+ argv: ['docs', '--json'],+ cwd: root,+ roots: [packageSet('0.6.8'), packageSet('0.7.0'), packageSet('0.7.0')],+ });+ expect(run.status).toBe(0);+ expect(run.report()).toMatchObject({+ version: '0.7.0',+ args: ['docs', '--json'],+ });+ expect(installedARelease(run.cache)).toBe(false);+ });++ it("runs a matching package set's own host entry with the same inputs, and settles with its result", () => {+ const root = brokenProject();+ const set = packageSet('0.7.0', {hostEntry: true});+ const run = host(+ {+ argv: ['component', 'Button'],+ cwd: root,+ roots: [set],+ cliCommand: 'acme astryx',+ integrations: ['acme-widgets'],+ },+ {sources: ACME_SOURCE},+ );+ expect(run.status).toBe(0);+ expect(run.report()).toEqual({+ hostEntry: '0.7.0',+ options: {+ argv: ['component', 'Button'],+ cwd: root,+ roots: [set],+ integrations: ['acme-widgets'],+ cliCommand: 'acme astryx',+ },+ discoverSources: ['Acme catalog'],+ });+ expect(run.result()).toEqual({+ status: 0,+ packages: [+ {name: '@astryxdesign/cli', version: '0.7.0', source: 'package-set'},+ ],+ });+ });++ it('installs nothing when no package set matches: this copy answers, announced', () => {+ const root = brokenProject();+ const roots = [packageSet('0.6.8')];+ const text = host({argv: ['--version'], cwd: root, roots});+ expect(text.status).toBe(0);+ expect(text.stdout.trim()).toBe(SELF_VERSION);+ expect(text.stderr).toContain(+ "astryx: could not get Astryx 0.7.0 to match this project's Core (no package set the host passed holds CLI 0.7.0 with this project's packages); answering with CLI",+ );+ expect(installedARelease(text.cache)).toBe(false);+ const json = host({argv: ['docs', '--json'], cwd: root, roots});+ expect(JSON.parse(json.stdout).meta.answeredBy.copy).toBe('fallback');+ expect(installedARelease(json.cache)).toBe(false);+ });++ it("installs nothing when the matching set's CLI starts through neither its host entry nor a bin: this copy answers, announced", () => {+ const root = brokenProject();+ const set = packageSet('0.7.0', {hostEntry: 'broken', bin: false});+ const run = host({argv: ['--version'], cwd: root, roots: [set]});+ expect(run.status).toBe(0);+ expect(run.stdout.trim()).toBe(SELF_VERSION);+ expect(run.stderr).toMatch(+ /astryx: could not get Astryx 0\.7\.0 to match this project's Core \(the CLI 0\.7\.0 in the package set at .+ could not be started\); answering with CLI/,+ );+ expect(run.stderr).not.toContain('installing CLI release');+ expect(installedARelease(run.cache)).toBe(false);+ });+});++describe('a project CLI the host declined, in a hosted run', () => {+ /** A project on Core and CLI 0.7.0, the CLI a stand-in that reports when it runs. */+ function projectWithCli() {+ const root = project(tempDir(), {+ '@astryxdesign/core': '0.7.0',+ '@astryxdesign/cli': '0.7.0',+ });+ installCore(root, '0.7.0');+ installStandInCli(root, '0.7.0');+ return root;+ }++ it("is answered by a package set of that CLI's release, through its host entry, with the reason", () => {+ const root = projectWithCli();+ const set = packageSet('0.7.0', {hostEntry: true});+ const run = host(+ {+ argv: ['docs'],+ cwd: root,+ roots: [packageSet('0.7.0'), set],+ declinedProjectCli: 'untrusted',+ },+ {sources: ACME_SOURCE},+ );+ expect(run.status).toBe(0);+ expect(run.stderr).not.toContain('stand-in');+ expect(run.report()).toEqual({+ hostEntry: '0.7.0',+ options: {+ argv: ['docs'],+ cwd: root,+ roots: [set],+ integrations: [],+ declinedProjectCli: 'untrusted',+ },+ discoverSources: ['Acme catalog'],+ });+ expect(run.result().packages).toEqual([+ {name: '@astryxdesign/cli', version: '0.7.0', source: 'package-set'},+ ]);+ });++ it('never runs it through a package set without a host entry: this copy answers, announced', () => {+ const root = projectWithCli();+ const run = host({+ argv: ['--version'],+ cwd: root,+ roots: [packageSet('0.7.0')],+ declinedProjectCli: 'untrusted',+ });+ expect(run.status).toBe(0);+ expect(run.stdout.trim()).toBe(SELF_VERSION);+ expect(run.stderr).not.toContain('stand-in');+ expect(run.stderr).toContain('(project CLI skipped: untrusted)');+ });+});++describe("the host's discover sources", () => {+ it("are called after every other source, and reported as the host's", () => {+ const empty = tempDir('empty');+ const run = host(+ {argv: ['discover', '--json'], cwd: empty},+ {sources: ACME_SOURCE},+ );+ expect(run.status).toBe(0);+ const out = JSON.parse(run.stdout);+ // The host's source comes after every other source and before the+ // official list, which is always last.+ expect(out.meta.sources).toEqual([+ expect.objectContaining({+ name: 'Acme catalog',+ from: 'the host',+ status: 'fresh',+ }),+ expect.objectContaining({name: 'Astryx'}),+ ]);+ expect(JSON.stringify(out.meta.available)).toContain('acme-widgets');+ });+});++describe("the host's discover sources in a project", () => {+ /**+ * JavaScript for a discover source whose catalog is named `name`.+ * @param {string} name+ */+ const source = name =>+ `async () => ({schemaVersion: 1, source: {name: ${JSON.stringify(name)}, generatedAt: '2026-10-20T00:00:00.000Z', complete: true}, packages: []})`;++ it("come after the project's own source and its integrations' sources, and before the official list", () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': SELF_VERSION,+ 'acme-widgets': '1.0.0',+ });+ fs.writeFileSync(+ path.join(root, 'astryx.config.mjs'),+ `export default {discover: ${source('Project catalog')}};\n`,+ );+ const pkgDir = path.join(root, 'node_modules', 'acme-widgets');+ writeJson(path.join(pkgDir, 'package.json'), {+ name: 'acme-widgets',+ version: '1.0.0',+ });+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ `export const discover = ${source('Widgets catalog')};\nexport default {};\n`,+ );+ const run = host(+ {argv: ['discover', '--json'], cwd: root},+ {sources: ACME_SOURCE},+ );+ expect(run.status).toBe(0);+ expect(+ JSON.parse(run.stdout).meta.sources.map(s => [s.name, s.from]),+ ).toEqual([+ ['Project catalog', 'astryx.config'],+ ['Widgets catalog', 'acme-widgets'],+ ['Acme catalog', 'the host'],+ ['Astryx', '@astryxdesign/cli'],+ ]);+ });+});++describe('what a hosted run resolved', () => {+ it('names the CLI and its Core from the package set outside a project', () => {+ const run = host({+ argv: ['component', '--list', '--json'],+ cwd: tempDir('empty'),+ });+ expect(run.status).toBe(0);+ expect(run.result().packages).toEqual(+ expect.arrayContaining([+ {+ name: '@astryxdesign/cli',+ version: SELF_VERSION,+ source: 'package-set',+ },+ {+ name: '@astryxdesign/core',+ version: SELF_VERSION,+ source: 'package-set',+ },+ ]),+ );+ });++ it("names a project's own integration as the project's", () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': SELF_VERSION,+ 'acme-widgets': '1.0.0',+ });+ const pkgDir = path.join(root, 'node_modules', 'acme-widgets');+ writeJson(path.join(pkgDir, 'package.json'), {+ name: 'acme-widgets',+ version: '1.0.0',+ });+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ const run = host({argv: ['discover', '--json'], cwd: root});+ expect(run.status).toBe(0);+ expect(run.result().packages).toContainEqual({+ name: 'acme-widgets',+ version: '1.0.0',+ source: 'project',+ });+ });+});diff --git a/packages/cli/foundation/runtime/locked-versions.mjs b/packages/cli/foundation/runtime/locked-versions.mjsnew file mode 100644index 0000000000..b99b9eefd6--- /dev/null+++ b/packages/cli/foundation/runtime/locked-versions.mjs@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The versions a project would install for the Astryx packages it+ * declares (architecture:cli-surface INV30): for each `@astryxdesign/*`+ * dependency, the value its package.json declares, the version its lockfile+ * records, and the version installed for it.+ *+ * @input A project folder.+ * @output One pin per declared `@astryxdesign/*` package.+ * @position foundation/runtime — read by package-set.mjs to match a project to+ * a host's package set.+ */++import * as path from 'node:path';+import {findLockfile, lockedVersion, readJson} from '../release/project.mjs';+import {resolveInstalledPackageDir} from '../integrations/autolink.mjs';++const SCOPE = '@astryxdesign/';+const FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies'];++/**+ * @typedef {object} AstryxPin+ * @property {string} name+ * @property {string} declared the value the project's package.json declares+ * @property {string | null} locked the version the project's lockfile records+ * @property {string | null} installed the version installed for the project+ */++/**+ * The project's `@astryxdesign/*` dependencies, in field then declaration+ * order; a name declared twice keeps its first field.+ * @param {string} projectDir the folder whose package.json declares them+ * @returns {AstryxPin[]}+ */+export function projectAstryxPins(projectDir) {+ const pkg = readJson(path.join(projectDir, 'package.json'));+ if (!pkg || typeof pkg !== 'object') return [];+ const lockfile = findLockfile(projectDir);+ /** @type {AstryxPin[]} */+ const pins = [];+ const seen = new Set();+ for (const field of FIELDS) {+ const deps = pkg[field];+ if (!deps || typeof deps !== 'object' || Array.isArray(deps)) continue;+ for (const [name, declared] of Object.entries(deps)) {+ if (!name.startsWith(SCOPE) || seen.has(name)) continue;+ if (typeof declared !== 'string') continue;+ seen.add(name);+ const found = resolveInstalledPackageDir(name, projectDir);+ const version = found+ ? readJson(path.join(found.packageDir, 'package.json'))?.version+ : null;+ pins.push({+ name,+ declared,+ locked: lockfile+ ? lockedVersion(lockfile, projectDir, name, declared)+ : null,+ installed: typeof version === 'string' ? version : null,+ });+ }+ }+ return pins;+}diff --git a/packages/cli/foundation/runtime/package-root.mjs b/packages/cli/foundation/runtime/package-root.mjsnew file mode 100644index 0000000000..af5feb40c8--- /dev/null+++ b/packages/cli/foundation/runtime/package-root.mjs@@ -0,0 +1,174 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The active hosted run (architecture:cli-surface INV30, spec AST-081+ * FR1): the package sets, approved integrations, and discover sources a host+ * passed through `@astryxdesign/cli/host`, the root that holds the copy that+ * started the run, and the packages the run resolved.+ *+ * Only the host entry activates a hosted run, once per process. With none+ * active, every lookup that consults it behaves as it does without a host.+ *+ * @input What the host entry passes to `activateHostedRun`.+ * @output `hostedRun()` for the lookups that consult it; the resolved-package+ * record the host entry returns.+ * @position foundation/runtime — read by the release choice, Core lookups,+ * computer-level integrations, and discover; written by host/index.mjs.+ */++import * as fs from 'node:fs';+import {relativeWithin, samePath} from '../fs/path-compare.mjs';++/**+ * @typedef {object} HostedRun+ * @property {readonly string[]} roots the host's package sets, in its order+ * @property {readonly string[]} integrations the integrations it approves for+ * use outside a project+ * @property {readonly Function[]} discoverSources its own discover sources+ * @property {string | null} startingRoot the root that holds the copy that+ * started the run+ * @property {string | null} projectRoot the project the run works in, if any+ * @property {((hostEntry: string) => Promise<(options: object) => Promise<{status: number, packages: Array<{name: string, version: string | null, source: 'project' | 'package-set'}>}>>) | null} loadHostEntry+ * loads another release's host entry, from one of the package sets, to hand+ * this run over to in this process+ */++/** @type {HostedRun | null} */+let active = null;++/** @type {Map<string, {name: string, version: string | null, dir: string | null, source: 'project' | 'package-set' | undefined}>} */+const resolved = new Map();++/**+ * @param {string} p+ * @returns {string}+ */+function real(p) {+ try {+ return fs.realpathSync(p);+ } catch {+ return p;+ }+}++/**+ * Start the hosted run of this process.+ * @param {{roots?: readonly string[], integrations?: readonly string[], discoverSources?: readonly Function[], startingRoot?: string | null, projectRoot?: string | null, loadHostEntry?: HostedRun['loadHostEntry']}} inputs+ * @returns {HostedRun}+ */+export function activateHostedRun({+ roots = [],+ integrations = [],+ discoverSources = [],+ startingRoot = null,+ projectRoot = null,+ loadHostEntry = null,+}) {+ if (active)+ throw new Error('A hosted run is already active in this process.');+ active = Object.freeze({+ roots: Object.freeze([...roots]),+ integrations: Object.freeze([...integrations]),+ discoverSources: Object.freeze([...discoverSources]),+ startingRoot,+ projectRoot,+ loadHostEntry,+ });+ return active;+}++/**+ * The hosted run of this process, or null when no host started it.+ * @returns {HostedRun | null}+ */+export function hostedRun() {+ return active;+}++/**+ * Note one package the run resolved. The first record of a name stands. Does+ * nothing outside a hosted run.+ * @param {string} name+ * @param {unknown} version+ * @param {string | null | undefined} dir+ * @param {'project' | 'package-set'} [source] where it came from, when the+ * caller knows; otherwise the folder that holds `dir` says+ */+export function recordResolved(name, version, dir, source) {+ if (!active || typeof name !== 'string' || resolved.has(name)) return;+ resolved.set(name, {+ name,+ version: typeof version === 'string' ? version : null,+ dir: dir ?? null,+ source,+ });+}++/**+ * Note every integration a project load resolved: one installed for the+ * computer, an approved one included, comes from a package set; any other,+ * from the project.+ * @param {ReadonlyArray<{name: string, version?: string, __packageDir?: string, __computer?: boolean}>} integrations+ */+export function recordResolvedIntegrations(integrations) {+ if (!active) return;+ for (const integration of integrations) {+ recordResolved(+ integration.name,+ integration.version,+ integration.__packageDir,+ integration.__computer ? 'package-set' : 'project',+ );+ }+}++/**+ * Where a package in `dir` came from: the deepest of the project and the+ * package sets (the root that holds the starting copy, and the roots the host+ * passed) that holds it. A root that is the project itself, as when the+ * host's CLI is installed in the project, counts as the project.+ * @param {string | null} dir+ * @returns {'project' | 'package-set'}+ */+function sourceOf(dir) {+ if (!active || !dir) return 'project';+ const target = real(dir);+ /** @type {Array<{base: string, source: 'project' | 'package-set'}>} */+ const holders = [];+ if (active.projectRoot) {+ holders.push({base: real(active.projectRoot), source: 'project'});+ }+ for (const root of [active.startingRoot, ...active.roots]) {+ if (root) holders.push({base: real(root), source: 'package-set'});+ }+ /** @type {{base: string, source: 'project' | 'package-set'} | null} */+ let best = null;+ for (const holder of holders) {+ const holds =+ samePath(holder.base, target) ||+ relativeWithin(holder.base, target) != null;+ // The project comes first, so it keeps a tie with a root that is itself.+ if (holds && (!best || holder.base.length > best.base.length))+ best = holder;+ }+ return best ? best.source : 'project';+}++/**+ * Each package the run resolved: its name, version, and whether it came from+ * the project or a package set (INV30).+ * @returns {Array<{name: string, version: string | null, source: 'project' | 'package-set'}>}+ */+export function resolvedPackages() {+ return [...resolved.values()].map(({name, version, dir, source}) => ({+ name,+ version,+ source: source ?? sourceOf(dir),+ }));+}++/** Forget the hosted run. Tests only. */+export function _resetHostedRun() {+ active = null;+ resolved.clear();+}diff --git a/packages/cli/foundation/runtime/package-set.mjs b/packages/cli/foundation/runtime/package-set.mjsnew file mode 100644index 0000000000..90cf1769fd--- /dev/null+++ b/packages/cli/foundation/runtime/package-set.mjs@@ -0,0 +1,130 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Matching a project to a host's package sets (architecture:cli-surface+ * INV30). A package set is a root whose `node_modules` holds a CLI, the Core+ * equal to it, and the integrations installed with them; a run resolves from at+ * most one root, and a hosted run installs nothing.+ *+ * Inside a project a root fills only the `@astryxdesign/*` packages the+ * project leaves uninstalled whose copy in the root ships no integration+ * manifest. For a run that a release other than the starting copy answers, the+ * first root in the host's order qualifies when its CLI and Core are that+ * release and it holds, for each package it may fill, the version the project+ * would install: the lockfile's, else a published version in the declared+ * range.+ *+ * @input A release, the project folder, and the host's roots.+ * @output The root that serves the run, or why none can.+ * @position foundation/runtime — read by the release choice (handoff.mjs) in a+ * hosted run.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {findManifestPaths} from '../integrations/integrations.mjs';+import {readJson} from '../release/project.mjs';+import {cliBinOf, isVersionRange} from '../release/cache.mjs';+import {isValidSemver, satisfiesRange} from '../env/semver.mjs';+import {projectAstryxPins} from './locked-versions.mjs';++const CLI = '@astryxdesign/cli';+const CORE = '@astryxdesign/core';++/**+ * A root's own copy of `name`, read from its `node_modules` only: a root never+ * reaches past itself.+ * @param {string} root+ * @param {string} name+ * @returns {{dir: string, version: string | null} | null}+ */+export function rootPackage(root, name) {+ const dir = path.join(root, 'node_modules', ...name.split('/'));+ const pkg = readJson(path.join(dir, 'package.json'));+ if (!pkg || typeof pkg !== 'object' || pkg.name !== name) return null;+ return {dir, version: typeof pkg.version === 'string' ? pkg.version : null};+}++/**+ * Whether `version` is one the project's install could bring in for `range`:+ * a plain version range only, and a prerelease only when the range names a+ * prerelease of the same version.+ * @param {string | null} version+ * @param {string} range+ * @returns {boolean}+ */+export function satisfiesInstall(version, range) {+ if (!version || !isValidSemver(version) || !isVersionRange(range)) {+ return false;+ }+ const dash = version.indexOf('-');+ if (dash !== -1 && !range.includes(`${version.slice(0, dash)}-`)) {+ return false;+ }+ return satisfiesRange(version, range);+}++/**+ * Whether `root` holds what the project would install for one pin it leaves+ * uninstalled. A package the root holds as an integration, or does not hold at+ * all, is one the root never fills, so it never keeps the root out.+ * @param {string} root+ * @param {import('./locked-versions.mjs').AstryxPin} pin+ * @returns {boolean}+ */+function holds(root, pin) {+ if (pin.name === CLI) return true;+ const copy = rootPackage(root, pin.name);+ if (!copy) return pin.name !== CORE;+ if (findManifestPaths(copy.dir).length > 0) return true;+ if (pin.locked) return copy.version === pin.locked;+ return satisfiesInstall(copy.version, pin.declared);+}++/**+ * @typedef {object} ServingRoot+ * @property {string} root+ * @property {string} cliDir the root's CLI package+ * @property {string | null} bin the root's `astryx` bin+ * @property {string | null} hostEntry the root's `host/index.mjs`, when its+ * CLI ships one+ */++/**+ * The first of `roots` that may serve a run in `projectDir` that CLI+ * `release` answers.+ * @param {{release: string, projectDir: string | null, roots: readonly string[], needsHostEntry?: boolean}} input+ * `needsHostEntry` keeps out a root whose CLI has no host entry+ * @returns {ServingRoot | {reason: string}}+ */+export function qualifyingRoot({+ release,+ projectDir,+ roots,+ needsHostEntry = false,+}) {+ const open = projectDir+ ? projectAstryxPins(projectDir).filter(pin => pin.installed === null)+ : [];+ for (const root of roots) {+ const cli = rootPackage(root, CLI);+ if (!cli || cli.version !== release) continue;+ const core = rootPackage(root, CORE);+ if (!core || core.version !== release) continue;+ const hostEntry = path.join(cli.dir, 'host', 'index.mjs');+ const hasHostEntry = fs.existsSync(hostEntry);+ if (needsHostEntry && !hasHostEntry) continue;+ const bin = cliBinOf(cli.dir);+ if (!bin && !hasHostEntry) continue;+ if (!open.every(pin => holds(root, pin))) continue;+ return {+ root,+ cliDir: cli.dir,+ bin,+ hostEntry: hasHostEntry ? hostEntry : null,+ };+ }+ return {+ reason: `no package set the host passed holds CLI ${release} with this project's packages`,+ };+}diff --git a/packages/cli/foundation/runtime/package-set.test.mjs b/packages/cli/foundation/runtime/package-set.test.mjsnew file mode 100644index 0000000000..23677e2c7c--- /dev/null+++ b/packages/cli/foundation/runtime/package-set.test.mjs@@ -0,0 +1,432 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Matching a project to a host's package sets (architecture:cli-surface+ * INV30): one root per run, the first that qualifies in the host's order, the+ * versions a project would install, nothing filled that ships an integration+ * manifest, and the integrations a host approves for use outside a project.+ */++import {describe, it, expect, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ cleanupFixtures,+ project,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';+import {projectAstryxPins} from './locked-versions.mjs';+import {qualifyingRoot, rootPackage, satisfiesInstall} from './package-set.mjs';+import {scanComputerIntegrations} from '../integrations/computer-integrations.mjs';+import {findCoreDir} from '../fs/paths.mjs';+import {+ _resetHostedRun,+ activateHostedRun,+ recordResolved,+ recordResolvedIntegrations,+ resolvedPackages,+} from './package-root.mjs';++afterEach(cleanupFixtures);++/**+ * Write a package into `dir`'s node_modules.+ * @param {string} dir+ * @param {string} name+ * @param {Record<string, unknown>} pkg+ * @param {{manifest?: boolean, bin?: boolean, hostEntry?: boolean}} [options]+ * @returns {string} the package folder+ */+function install(dir, name, pkg, options = {}) {+ const pkgDir = path.join(dir, 'node_modules', ...name.split('/'));+ writeJson(path.join(pkgDir, 'package.json'), {+ name,+ ...pkg,+ ...(options.bin ? {bin: {astryx: './bin.cjs'}} : {}),+ });+ if (options.bin) fs.writeFileSync(path.join(pkgDir, 'bin.cjs'), '');+ if (options.hostEntry) {+ fs.mkdirSync(path.join(pkgDir, 'host'), {recursive: true});+ fs.writeFileSync(path.join(pkgDir, 'host', 'index.mjs'), '');+ }+ if (options.manifest) {+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ }+ return pkgDir;+}++/**+ * A package set: a root holding a CLI and Core of `version`.+ * @param {string} version+ * @param {{hostEntry?: boolean, bin?: boolean}} [options]+ * @returns {string}+ */+function packageSet(version, options = {}) {+ const root = tempDir('set');+ install(+ root,+ '@astryxdesign/cli',+ {version},+ {bin: options.bin ?? true, hostEntry: options.hostEntry},+ );+ install(root, '@astryxdesign/core', {version});+ return root;+}++describe('the versions a project would install', () => {+ it('reads each declared @astryxdesign/* package with its lockfile and installed versions', () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': '^0.7.0',+ '@astryxdesign/cli': '0.7.0',+ react: '^19.0.0',+ });+ install(root, '@astryxdesign/cli', {version: '0.7.0'});+ writeJson(path.join(root, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {+ '': {},+ 'node_modules/@astryxdesign/core': {version: '0.7.1'},+ 'node_modules/@astryxdesign/cli': {version: '0.7.0'},+ },+ });+ expect(projectAstryxPins(root)).toEqual([+ {+ name: '@astryxdesign/core',+ declared: '^0.7.0',+ locked: '0.7.1',+ installed: null,+ },+ {+ name: '@astryxdesign/cli',+ declared: '0.7.0',+ locked: '0.7.0',+ installed: '0.7.0',+ },+ ]);+ });+});++describe('a version the project would install for a range', () => {+ it.each([+ ['0.7.1', '^0.7.0', true],+ ['0.8.0', '^0.7.0', false],+ ['0.7.1-canary.1', '^0.7.0', false],+ ['0.7.1-canary.1', '^0.7.1-canary.0', true],+ ['0.7.1', 'file:../core', false],+ ['0.7.1', 'workspace:*', false],+ [null, '^0.7.0', false],+ ])('%s for %s: %s', (version, range, expected) => {+ expect(satisfiesInstall(version, range)).toBe(expected);+ });+});++describe('the package set that serves a run another release answers', () => {+ it('serves from the first set whose CLI and Core are that release', () => {+ const older = packageSet('0.6.8');+ const first = packageSet('0.7.0');+ const second = packageSet('0.7.0');+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ const served = qualifyingRoot({+ release: '0.7.0',+ projectDir: root,+ roots: [older, first, second],+ });+ expect(served).toMatchObject({root: first, hostEntry: null});+ expect(/** @type {any} */ (served).bin).toBe(+ path.join(first, 'node_modules', '@astryxdesign', 'cli', 'bin.cjs'),+ );+ });++ it('skips a set whose Core is another release, or missing', () => {+ const mixed = tempDir('set');+ install(mixed, '@astryxdesign/cli', {version: '0.7.0'}, {bin: true});+ install(mixed, '@astryxdesign/core', {version: '0.7.1'});+ const bare = tempDir('set');+ install(bare, '@astryxdesign/cli', {version: '0.7.0'}, {bin: true});+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ expect(+ qualifyingRoot({+ release: '0.7.0',+ projectDir: root,+ roots: [mixed, bare],+ }),+ ).toEqual({+ reason:+ "no package set the host passed holds CLI 0.7.0 with this project's packages",+ });+ });++ it("holds the lockfile's version of each package it fills, else one in the declared range", () => {+ const locked = project(tempDir(), {+ '@astryxdesign/core': '^0.7.0',+ '@astryxdesign/charts': '^0.7.0',+ });+ writeJson(path.join(locked, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {+ '': {},+ 'node_modules/@astryxdesign/core': {version: '0.7.0'},+ 'node_modules/@astryxdesign/charts': {version: '0.7.0'},+ },+ });+ const newer = packageSet('0.7.0');+ install(newer, '@astryxdesign/charts', {version: '0.7.2'});+ const exact = packageSet('0.7.0');+ install(exact, '@astryxdesign/charts', {version: '0.7.0'});+ expect(+ qualifyingRoot({+ release: '0.7.0',+ projectDir: locked,+ roots: [newer, exact],+ }),+ ).toMatchObject({root: exact});++ const ranged = project(tempDir(), {+ '@astryxdesign/core': '^0.7.0',+ '@astryxdesign/charts': '^0.7.0',+ });+ expect(+ qualifyingRoot({release: '0.7.0', projectDir: ranged, roots: [newer]}),+ ).toMatchObject({root: newer});+ });++ it('keeps out a set whose copy the project declares as a path and has not locked', () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': '0.7.0',+ '@astryxdesign/charts': 'file:../charts',+ });+ const set = packageSet('0.7.0');+ install(set, '@astryxdesign/charts', {version: '0.7.0'});+ expect(+ qualifyingRoot({release: '0.7.0', projectDir: root, roots: [set]}),+ ).toHaveProperty('reason');+ });++ it('never fills an @astryxdesign/* integration, so its version never keeps a set out', () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': '0.7.0',+ '@astryxdesign/richtext': '^0.9.0',+ });+ const set = packageSet('0.7.0');+ install(+ set,+ '@astryxdesign/richtext',+ {version: '0.7.0'},+ {manifest: true},+ );+ expect(+ qualifyingRoot({release: '0.7.0', projectDir: root, roots: [set]}),+ ).toMatchObject({root: set});+ });++ it('fills nothing the project installed', () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': '0.7.0',+ '@astryxdesign/charts': '^0.6.0',+ });+ install(root, '@astryxdesign/charts', {version: '0.6.3'});+ const set = packageSet('0.7.0');+ install(set, '@astryxdesign/charts', {version: '0.7.0'});+ expect(+ qualifyingRoot({release: '0.7.0', projectDir: root, roots: [set]}),+ ).toMatchObject({root: set});+ });++ it('needs a host entry when asked to', () => {+ const plain = packageSet('0.7.0');+ const hosted = packageSet('0.7.0', {hostEntry: true});+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ expect(+ qualifyingRoot({+ release: '0.7.0',+ projectDir: root,+ roots: [plain, hosted],+ needsHostEntry: true,+ }),+ ).toMatchObject({+ root: hosted,+ hostEntry: path.join(+ hosted,+ 'node_modules',+ '@astryxdesign',+ 'cli',+ 'host',+ 'index.mjs',+ ),+ });+ });++ it("reads a root's own node_modules only", () => {+ const outer = tempDir('outer');+ install(outer, '@astryxdesign/core', {version: '0.7.0'});+ const set = path.join(outer, 'set');+ install(set, '@astryxdesign/cli', {version: '0.7.0'}, {bin: true});+ expect(rootPackage(set, '@astryxdesign/core')).toBeNull();+ expect(+ qualifyingRoot({release: '0.7.0', projectDir: null, roots: [set]}),+ ).toHaveProperty('reason');+ });+});++describe('the integrations a host approves', () => {+ it('load by name from the package set that holds the CLI, with the same checks', () => {+ const set = tempDir('set');+ const cliDir = install(set, '@astryxdesign/cli', {version: '0.7.2'});+ // The set declares only the CLI and Core, so FR12's scan finds nothing.+ writeJson(path.join(set, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '0.7.2'},+ });+ install(set, 'acme-widgets', {version: '1.0.0'}, {manifest: true});+ install(+ set,+ 'acme-old',+ {version: '1.0.0', peerDependencies: {'@astryxdesign/core': '^0.6.0'}},+ {manifest: true},+ );+ install(set, 'acme-plain', {version: '1.0.0'});+ expect(+ scanComputerIntegrations({cliRoot: cliDir, release: '0.7.2'}),+ ).toEqual([]);+ const found = scanComputerIntegrations({+ cliRoot: cliDir,+ release: '0.7.2',+ approved: ['acme-widgets', 'acme-old', 'acme-plain', 'acme-missing'],+ });+ expect(found.map(c => [c.name, c.incompatible])).toEqual([+ ['acme-widgets', null],+ [+ 'acme-old',+ "it needs @astryxdesign/core ^0.6.0, and this computer's CLI is 0.7.2",+ ],+ ]);+ expect(found[0].packageDir).toBe(+ path.join(set, 'node_modules', 'acme-widgets'),+ );+ });++ it('never takes an approved name from a folder above the package set', () => {+ const outer = tempDir('outer');+ install(outer, 'acme-outer', {version: '1.0.0'}, {manifest: true});+ const set = path.join(outer, 'set');+ const cliDir = install(set, '@astryxdesign/cli', {version: '0.7.2'});+ writeJson(path.join(set, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '0.7.2'},+ });+ expect(+ scanComputerIntegrations({+ cliRoot: cliDir,+ release: '0.7.2',+ approved: ['acme-outer'],+ }),+ ).toEqual([]);+ });+});++describe('where each package a hosted run resolved came from', () => {+ afterEach(() => _resetHostedRun());++ /**+ * @param {string} root+ * @param {string} name+ */+ const at = (root, name) =>+ path.join(root, 'node_modules', ...name.split('/'));++ it("names the project's packages as the project's when the host's CLI is installed in the project", () => {+ const app = tempDir('app');+ activateHostedRun({startingRoot: app, projectRoot: app});+ recordResolved('@astryxdesign/cli', '0.7.2', at(app, '@astryxdesign/cli'));+ recordResolved(+ '@astryxdesign/core',+ '0.7.2',+ at(app, '@astryxdesign/core'),+ 'project',+ );+ recordResolvedIntegrations([+ {+ name: 'acme-widgets',+ version: '1.0.0',+ __packageDir: at(app, 'acme-widgets'),+ },+ ]);+ expect(resolvedPackages()).toEqual([+ {name: '@astryxdesign/cli', version: '0.7.2', source: 'project'},+ {name: '@astryxdesign/core', version: '0.7.2', source: 'project'},+ {name: 'acme-widgets', version: '1.0.0', source: 'project'},+ ]);+ });++ it("names what a package set holds as the package set's, and the project's integrations as the project's", () => {+ const set = tempDir('set');+ const app = tempDir('app');+ activateHostedRun({startingRoot: set, projectRoot: app});+ recordResolved('@astryxdesign/cli', '0.7.2', at(set, '@astryxdesign/cli'));+ recordResolved(+ '@astryxdesign/core',+ '0.7.2',+ at(set, '@astryxdesign/core'),+ );+ recordResolvedIntegrations([+ {+ name: 'acme-tools',+ version: '2.0.0',+ __packageDir: at(set, 'acme-tools'),+ __computer: true,+ },+ {+ name: 'acme-widgets',+ version: '1.0.0',+ __packageDir: at(app, 'acme-widgets'),+ },+ ]);+ expect(resolvedPackages()).toEqual([+ {name: '@astryxdesign/cli', version: '0.7.2', source: 'package-set'},+ {name: '@astryxdesign/core', version: '0.7.2', source: 'package-set'},+ {name: 'acme-tools', version: '2.0.0', source: 'package-set'},+ {name: 'acme-widgets', version: '1.0.0', source: 'project'},+ ]);+ });++ it("names what the project loaded or found above itself, as a workspace hoists it, as the project's", () => {+ // The host's CLI sits in the workspace root, which is its package set,+ // and the project is a workspace package whose packages are hoisted there.+ const mono = tempDir('mono');+ writeJson(path.join(mono, 'package.json'), {+ private: true,+ workspaces: ['packages/*'],+ });+ const app = path.join(mono, 'packages', 'app');+ writeJson(path.join(app, 'package.json'), {+ name: 'app',+ dependencies: {'@astryxdesign/core': '0.7.2', 'acme-widgets': '1.0.0'},+ });+ install(mono, '@astryxdesign/core', {version: '0.7.2'});+ activateHostedRun({startingRoot: mono, projectRoot: app});+ expect(findCoreDir(app)).toBe(at(mono, '@astryxdesign/core'));+ recordResolvedIntegrations([+ {+ name: 'acme-widgets',+ version: '1.0.0',+ __packageDir: at(mono, 'acme-widgets'),+ },+ ]);+ expect(resolvedPackages()).toEqual([+ {name: '@astryxdesign/core', version: '0.7.2', source: 'project'},+ {name: 'acme-widgets', version: '1.0.0', source: 'project'},+ ]);+ });++ it('names a package set inside the project folder as a package set', () => {+ const app = tempDir('app');+ const set = path.join(app, '.tools', 'astryx');+ activateHostedRun({startingRoot: set, projectRoot: app});+ recordResolved('@astryxdesign/cli', '0.7.2', at(set, '@astryxdesign/cli'));+ expect(resolvedPackages()).toEqual([+ {name: '@astryxdesign/cli', version: '0.7.2', source: 'package-set'},+ ]);+ });+});diff --git a/packages/cli/host/door-conformance.test.mjs b/packages/cli/host/door-conformance.test.mjsnew file mode 100644index 0000000000..490f0d3c3d--- /dev/null+++ b/packages/cli/host/door-conformance.test.mjs@@ -0,0 +1,274 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Door conformance (spec AST-081 FR1): every command example, run+ * through the bin and through the host entry, gives the same exit status,+ * output, and file changes, in an empty folder, a project on the current+ * minor, and a project on the previous minor.+ *+ * Each run is a child process with its own copy of the folder, its own home+ * folder, and its own per-user cache. The package registry is unreachable and+ * notices are off, so no run reaches the network. Output is compared once each+ * run's own folders read as placeholders. Neither door is given a command+ * name, so FR5's command names are the same through both, and no line FR5 or+ * FR6 lets differ prints.+ */++import {spawn} from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const CLI_ROOT = path.resolve(HERE, '..');+const CORE_ROOT = path.resolve(CLI_ROOT, '../core');+const BIN = path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');+const HOST_URL = pathToFileURL(path.join(HERE, 'index.mjs')).href;+const COMMANDS = path.join(CLI_ROOT, 'clients', 'cli', 'commands');+const VERSION = JSON.parse(+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf8'),+).version;+const [MAJOR, MINOR] = VERSION.split('.').map(Number);+const PREVIOUS_MINOR = `${MAJOR}.${Math.max(MINOR - 1, 0)}.0`;+/** How long one run may take before it counts as hung. */+const RUN_TIMEOUT_MS = 90_000;++/** Split an example's command line the way a shell would, quotes included. */+function splitArgs(line) {+ const out = [];+ let current = '';+ let quote = null;+ let started = false;+ for (const ch of line) {+ if (quote) {+ if (ch === quote) quote = null;+ else current += ch;+ } else if (ch === '"' || ch === "'") {+ quote = ch;+ started = true;+ } else if (/\s/.test(ch)) {+ if (current || started) out.push(current);+ current = '';+ started = false;+ } else {+ current += ch;+ }+ }+ if (current || started) out.push(current);+ return out;+}++/** @returns {Promise<Array<{cli: string, argv: string[]}>>} every distinct command example */+async function commandExamples() {+ /** @type {Map<string, string[]>} */+ const byLine = new Map();+ for (const name of fs.readdirSync(COMMANDS).sort()) {+ if (!name.endsWith('.doc.mjs')) continue;+ const {doc} = await import(pathToFileURL(path.join(COMMANDS, name)).href);+ if (doc?.type !== 'command') continue;+ for (const example of doc.examples ?? []) {+ const words = splitArgs(example.cli);+ byLine.set(example.cli, words[0] === 'astryx' ? words.slice(1) : words);+ }+ }+ return [...byLine].map(([cli, argv]) => ({cli, argv}));+}++/**+ * @param {string} file+ * @param {unknown} value+ */+function writeJson(file, value) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n');+}++/** The folders every example runs in, each set up fresh for each run. */+const FOLDERS = {+ 'an empty folder': () => {},+ /** @param {string} dir */+ 'a project on the current minor': dir => {+ writeJson(path.join(dir, 'package.json'), {+ name: 'app',+ private: true,+ dependencies: {'@astryxdesign/core': VERSION},+ });+ const scope = path.join(dir, 'node_modules', '@astryxdesign');+ fs.mkdirSync(scope, {recursive: true});+ fs.symlinkSync(CORE_ROOT, path.join(scope, 'core'), 'dir');+ },+ /** @param {string} dir */+ 'a project on the previous minor': dir => {+ writeJson(path.join(dir, 'package.json'), {+ name: 'app',+ private: true,+ dependencies: {'@astryxdesign/core': PREVIOUS_MINOR},+ });+ writeJson(+ path.join(dir, 'node_modules', '@astryxdesign', 'core', 'package.json'),+ {name: '@astryxdesign/core', version: PREVIOUS_MINOR},+ );+ },+};++/** @type {string[]} */+const bases = [];++/**+ * Every file under `root`, skipping node_modules, by path relative to `base`.+ * @param {string} root+ * @param {string} base+ * @param {Map<string, string>} into+ */+function readTree(root, base, into = new Map()) {+ if (!fs.existsSync(root)) return into;+ for (const entry of fs.readdirSync(root, {withFileTypes: true})) {+ const file = path.join(root, entry.name);+ if (entry.isDirectory() && entry.name !== 'node_modules') {+ readTree(file, base, into);+ } else if (entry.isFile()) {+ into.set(path.relative(base, file), fs.readFileSync(file, 'utf8'));+ }+ }+ return into;+}++/**+ * Run one example through one door in a fresh copy of a folder.+ * @param {'bin' | 'host entry'} door+ * @param {string[]} argv+ * @param {(dir: string) => void} setUp+ * @returns {Promise<{status: number | null, stdout: string, stderr: string, changes: Record<string, string | null>}>}+ */+async function runThrough(door, argv, setUp) {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-door-'));+ bases.push(base);+ const dir = path.join(base, 'app');+ const home = path.join(base, 'home');+ fs.mkdirSync(dir);+ fs.mkdirSync(home);+ setUp(dir);+ const read = () => readTree(home, base, readTree(dir, base));+ const before = read();+ const args =+ door === 'bin'+ ? [BIN, ...argv]+ : [+ '--input-type=module',+ '-e',+ `import {runHostedCli} from ${JSON.stringify(HOST_URL)};\n` ++ `const result = await runHostedCli({argv: ${JSON.stringify(argv)}, cwd: process.cwd()});\n` ++ 'process.exitCode = result.status;\n',+ ];+ const env = {...process.env};+ for (const key of Object.keys(env)) {+ if (key.startsWith('VITEST') || key === 'NODE_OPTIONS') delete env[key];+ }+ Object.assign(env, {+ HOME: home,+ USERPROFILE: home,+ XDG_CACHE_HOME: path.join(base, 'cache'),+ XDG_CONFIG_HOME: path.join(home, '.config'),+ XDG_DATA_HOME: path.join(home, '.local', 'share'),+ // Other tools' own state, such as the device id the gh tool writes when+ // swizzle asks it whether it is signed in, and npm's cache and logs,+ // stays outside the folders the runs compare.+ XDG_STATE_HOME: path.join(base, 'state'),+ npm_config_cache: path.join(base, 'npm-cache'),+ CI: '1',+ NO_UPDATE_NOTIFIER: '1',+ NO_COLOR: '1',+ npm_config_registry: 'http://127.0.0.1:9/',+ npm_config_fetch_retries: '0',+ npm_config_fetch_timeout: '2000',+ });+ const child = spawn(process.execPath, args, {+ cwd: dir,+ env,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', chunk => (stdout += chunk));+ child.stderr.on('data', chunk => (stderr += chunk));+ const timer = setTimeout(() => child.kill('SIGKILL'), RUN_TIMEOUT_MS);+ const status = await new Promise(resolve => child.on('close', resolve));+ clearTimeout(timer);+ // Each run's own folders read as placeholders.+ const real = fs.realpathSync(base);+ /** @param {string} text */+ const placeholders = text =>+ text.split(real).join('<run>').split(base).join('<run>');+ const after = read();+ /** @type {Record<string, string | null>} */+ const changes = {};+ for (const [file, text] of after) {+ if (before.get(file) !== text) changes[file] = placeholders(text);+ }+ for (const file of before.keys()) {+ if (!after.has(file)) changes[file] = null;+ }+ return {+ status,+ stdout: placeholders(stdout),+ stderr: placeholders(stderr),+ changes,+ };+}++/**+ * Run `tasks` with at most `limit` at a time.+ * @template T+ * @param {Array<() => Promise<T>>} tasks+ * @param {number} limit+ * @returns {Promise<T[]>}+ */+async function inBatches(tasks, limit) {+ const results = new Array(tasks.length);+ let next = 0;+ const worker = async () => {+ while (next < tasks.length) {+ const index = next++;+ results[index] = await tasks[index]();+ }+ };+ await Promise.all(Array.from({length: limit}, worker));+ return results;+}++const examples = await commandExamples();++afterAll(() => {+ for (const base of bases) fs.rmSync(base, {recursive: true, force: true});+});++describe.each(Object.entries(FOLDERS))('in %s', (_folder, setUp) => {+ /** @type {Map<string, {bin: Awaited<ReturnType<typeof runThrough>>, host: Awaited<ReturnType<typeof runThrough>>}>} */+ const runs = new Map();++ beforeAll(async () => {+ const limit = Math.max(2, Math.min(16, os.availableParallelism()));+ const results = await inBatches(+ examples.flatMap(({argv}) => [+ () => runThrough('bin', argv, setUp),+ () => runThrough('host entry', argv, setUp),+ ]),+ limit,+ );+ examples.forEach(({cli}, index) => {+ runs.set(cli, {bin: results[2 * index], host: results[2 * index + 1]});+ });+ }, 15 * 60_000);++ it('runs every example', () => {+ expect(examples.length).toBeGreaterThan(100);+ });++ it.each(examples.map(({cli}) => [cli]))('%s', cli => {+ const {bin, host} = runs.get(cli) ?? {};+ expect(bin?.status, `${cli} finished through the bin`).not.toBeNull();+ expect(host).toEqual(bin);+ });+});diff --git a/packages/cli/host/index.d.ts b/packages/cli/host/index.d.tsnew file mode 100644index 0000000000..2897618cb1--- /dev/null+++ b/packages/cli/host/index.d.ts@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * `@astryxdesign/cli/host`: the programmatic host entry. A tool that carries+ * this CLI starts one run of it per process with explicit inputs+ * (`spec:AST-081` FR1).+ */++import type {DiscoverSource} from '../authoring/discover/type.js';++/** The inputs of one hosted run. Every option is optional. */+export interface HostedCliOptions {+ /** The arguments after `astryx`. Default: none. */+ argv?: readonly string[];+ /**+ * The working folder of the run. The run changes the process's working+ * folder to it, finds its project there, and writes where the command+ * writes from there. Default: the process's working folder.+ */+ cwd?: string;+ /**+ * The command the tool's users type to run the CLI, such as+ * `acme astryx`. Printed commands start with it unless the integrations+ * the run loads declare their own. A non-blank single line of at most 120+ * characters, with no surrounding spaces and no Astryx agent-docs marker+ * text. Default: none; printed commands use the package manager's name.+ */+ cliCommand?: string;+ /**+ * When the tool found the project's own CLI and did not run it, why, in the+ * tool's own words, such as `cannot-start` or `untrusted`: a non-blank+ * single line of at most 120 characters, with no surrounding spaces. The+ * run is then never handed to that CLI: its release answers in its place+ * when this copy, or a package set's host entry, is that release;+ * otherwise this copy answers with one warning line naming the reason and+ * `meta.answeredBy.copy` set to `fallback`. Default: none; a project's own+ * CLI answers its project.+ */+ declinedProjectCli?: string;+ /**+ * The tool's package sets, in its order of preference: folders whose+ * `node_modules` each hold a CLI, the Core equal to it, and the+ * integrations installed with them. Inside a project, a set fills only the+ * `@astryxdesign/*` packages the project leaves uninstalled that are not+ * integrations. When a release other than this copy answers the folder,+ * the first set whose CLI and Core are that release and that holds what the+ * project would install for those packages serves the run. A run never+ * installs a release: with no such set, this copy answers with one warning+ * line. Default: none.+ */+ roots?: readonly string[];+ /**+ * Integrations the tool approves for use outside a project, by package+ * name. Each loads from the package set that serves the run, as an+ * integration installed for the computer does, and a name that set does not+ * hold is left out. Default: none.+ */+ integrations?: readonly string[];+ /**+ * The tool's own discover sources. `astryx discover` calls them after every+ * integration's source and before the official list, and reports each as+ * the host's. Another package set's host entry that answers the run gets+ * them too; a run handed to a CLI's bin does not. Default: none.+ */+ discoverSources?: readonly DiscoverSource[];+}++/** One package a hosted run resolved. */+export interface HostedPackage {+ /** The package name. */+ name: string;+ /** Its version, or null when its package.json gives none. */+ version: string | null;+ /** Whether it came from the project or from a package set. */+ source: 'project' | 'package-set';+}++/**+ * The outcome of a hosted run that returned: this copy's, or, when another+ * package set's release answered through its own host entry, that entry's.+ */+export interface HostedCliResult {+ /** The run's exit status, as the `astryx` bin would exit. */+ status: number;+ /** Each package the run resolved: the CLI, its Core, and its integrations. */+ packages: HostedPackage[];+}++/**+ * Run the CLI once in this process, as the `astryx` bin would with the same+ * arguments in the same folder.+ *+ * The run owns the process's working folder, arguments, standard streams,+ * and exit. The call settles when the command returns. Like the bin, the run+ * instead ends the process, with the exit status the bin would exit with, and+ * the call never settles, when it:+ * - prints help or the version (`--help`, `-h`, `help`, `--version`, `-V`,+ * `--version --json`), with status 0;+ * - rejects the command line, such as an unknown command or option;+ * - reports an error it stops on, including every error in `--json` mode;+ * - meets an unexpected error, with status 1;+ * - hands the run to another CLI's bin: the project's own CLI when+ * `declinedProjectCli` is absent, or a package set whose CLI ships no host+ * entry.+ *+ * When another package set's release answers through its own host entry,+ * that entry runs in this process with the same inputs, and the call settles+ * with its result.+ *+ * Rejects with a `TypeError`, before anything runs, for an unknown option or+ * an invalid value; and with an `Error`, before anything runs, when a run has+ * already started in this process.+ */+export declare function runHostedCli(+ options?: HostedCliOptions,+): Promise<HostedCliResult>;diff --git a/packages/cli/host/index.mjs b/packages/cli/host/index.mjsnew file mode 100644index 0000000000..061c5258b2--- /dev/null+++ b/packages/cli/host/index.mjs@@ -0,0 +1,295 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `@astryxdesign/cli/host`, the programmatic host entry (spec AST-081+ * FR1). A tool that carries this CLI starts one run of it with explicit+ * inputs: the arguments, the working folder, the command name its users type,+ * and, when it found the project's own CLI and did not run it, the reason.+ *+ * Its package sets, the integrations it approves, and its own discover sources+ * are matched, loaded, and recorded as architecture:cli-surface INV30 says; a+ * hosted run installs nothing. When another package set's release answers+ * through its own host entry, that entry runs in this process with the same+ * inputs, and the call settles with its result.+ *+ * @input `runHostedCli` options (see host/index.d.ts for the contract).+ * @output The run's exit status and the packages it resolved, each with its+ * source. The run owns the process's working folder, arguments, standard+ * streams, and exit, exactly as a run of the `astryx` bin does: every path+ * on which the bin exits the process exits it here too (host/index.d.ts+ * lists them).+ * @position host — the package's `./host` export; calls clients/cli/run.mjs.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';++const CLI_ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+);+const BIN = path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');++/**+ * The process, seen as the holder of one mark: whether a hosted run started in+ * it, whichever copy of the CLI started it.+ */+const processMarks = /** @type {{__astryxHostRunStarted?: boolean}} */ (+ /** @type {unknown} */ (process)+);++/** The longest reason a host may give for not running the project's CLI. */+const MAX_REASON_LENGTH = 120;++const OPTION_NAMES = new Set([+ 'argv',+ 'cwd',+ 'cliCommand',+ 'declinedProjectCli',+ 'roots',+ 'integrations',+ 'discoverSources',+]);++/** A bare npm package name, scoped or not. */+const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/u;++/**+ * @param {string} message+ * @returns {TypeError}+ */+function invalid(message) {+ return new TypeError(`runHostedCli: ${message}`);+}++/**+ * Check every input before anything runs.+ * @param {unknown} options+ * @returns {Promise<{argv: string[], cwd: string, cliCommand: string | undefined, declinedProjectCli: string | undefined, roots: string[], integrations: string[], discoverSources: Function[]}>}+ */+async function readOptions(options) {+ if (options === undefined) options = {};+ if (+ options === null ||+ typeof options !== 'object' ||+ Array.isArray(options)+ ) {+ throw invalid('options must be an object');+ }+ const record = /** @type {Record<string, unknown>} */ (options);+ for (const key of Object.keys(record)) {+ if (!OPTION_NAMES.has(key)) {+ throw invalid(+ `unknown option "${key}"; the options are ${[...OPTION_NAMES].join(', ')}`,+ );+ }+ }++ const argv = record.argv ?? [];+ if (!Array.isArray(argv) || !argv.every(arg => typeof arg === 'string')) {+ throw invalid('argv must be an array of strings');+ }++ const cwdInput = record.cwd ?? process.cwd();+ if (typeof cwdInput !== 'string' || cwdInput === '') {+ throw invalid('cwd must be a folder path');+ }+ const cwd = path.resolve(cwdInput);+ let isFolder = false;+ try {+ isFolder = fs.statSync(cwd).isDirectory();+ } catch {+ isFolder = false;+ }+ if (!isFolder) throw invalid(`cwd is not a folder: ${cwd}`);++ let cliCommand;+ if (record.cliCommand !== undefined) {+ const {parseCliCommandField} =+ await import('../authoring/integration/schema.mjs');+ try {+ cliCommand = parseCliCommandField(record.cliCommand, 'cliCommand');+ } catch (err) {+ throw invalid(err instanceof Error ? err.message : String(err));+ }+ }++ const declinedProjectCli = record.declinedProjectCli;+ if (+ declinedProjectCli !== undefined &&+ (typeof declinedProjectCli !== 'string' ||+ declinedProjectCli === '' ||+ declinedProjectCli !== declinedProjectCli.trim() ||+ /[\r\n]/u.test(declinedProjectCli) ||+ declinedProjectCli.length > MAX_REASON_LENGTH)+ ) {+ throw invalid(+ `declinedProjectCli must be a non-blank single line of at most ${MAX_REASON_LENGTH} characters, with no surrounding spaces`,+ );+ }++ const rootsInput = record.roots ?? [];+ if (+ !Array.isArray(rootsInput) ||+ !rootsInput.every(root => typeof root === 'string' && root !== '')+ ) {+ throw invalid('roots must be an array of folder paths');+ }+ /** @type {string[]} */+ const roots = [];+ for (const root of rootsInput) {+ const folder = path.resolve(root);+ let isRoot = false;+ try {+ isRoot = fs.statSync(folder).isDirectory();+ } catch {+ isRoot = false;+ }+ if (!isRoot) {+ throw invalid(`roots names a path that is not a folder: ${folder}`);+ }+ if (!roots.includes(folder)) roots.push(folder);+ }++ const integrations = record.integrations ?? [];+ if (+ !Array.isArray(integrations) ||+ !integrations.every(+ name => typeof name === 'string' && PACKAGE_NAME.test(name),+ )+ ) {+ throw invalid('integrations must be an array of package names');+ }++ const discoverSources = record.discoverSources ?? [];+ if (+ !Array.isArray(discoverSources) ||+ !discoverSources.every(source => typeof source === 'function')+ ) {+ throw invalid('discoverSources must be an array of functions');+ }++ return {+ argv: [...argv],+ cwd,+ cliCommand,+ declinedProjectCli: /** @type {string | undefined} */ (declinedProjectCli),+ roots,+ integrations: [...new Set(/** @type {string[]} */ (integrations))],+ discoverSources: [...discoverSources],+ };+}++/**+ * The bin's Node version gate, for a host process: same message, same exit+ * status, same JSON envelope.+ * @param {string[]} argv+ * @returns {Promise<boolean>} whether the run may go on+ */+async function nodeVersionGate(argv) {+ const {isNodeVersionSupported, unsupportedNodeMessage} =+ await import('../foundation/env/node-version.mjs');+ if (isNodeVersionSupported(process.versions.node)) return true;+ const msg = unsupportedNodeMessage(process.versions.node);+ if (argv.includes('--json')) {+ process.stdout.write(+ `${JSON.stringify({apiVersion: 1, error: msg, code: 'ERR_NODE_VERSION'}, null, 2)}\n`,+ );+ } else {+ process.stderr.write(`${msg}\n`);+ }+ process.exitCode = 1;+ return false;+}++/**+ * Load another release's host entry, from one of the host's package sets, to+ * hand this run over to in this process (architecture:cli-surface INV30). The+ * run stays one call of the host's: the one-call mark passes to the entry that+ * answers, and the call settles with that entry's result.+ * @param {string} hostEntry the package set's `host/index.mjs`+ * @returns {Promise<(options: import('./index.js').HostedCliOptions) => Promise<import('./index.js').HostedCliResult>>}+ */+async function loadHostEntry(hostEntry) {+ const entry = await import(pathToFileURL(hostEntry).href);+ if (typeof entry.runHostedCli !== 'function') {+ throw new Error(`${hostEntry} exports no runHostedCli`);+ }+ return options => {+ processMarks.__astryxHostRunStarted = false;+ return entry.runHostedCli(options);+ };+}++/**+ * Run the CLI once in this process, as the `astryx` bin would run with the+ * same arguments in the same folder, for a tool that carries this CLI.+ *+ * @param {import('./index.js').HostedCliOptions} [options]+ * @returns {Promise<import('./index.js').HostedCliResult>}+ */+export async function runHostedCli(options) {+ const input = await readOptions(options);+ if (processMarks.__astryxHostRunStarted) {+ throw new Error(+ 'runHostedCli: a run already started in this process; start each run in a new process',+ );+ }+ processMarks.__astryxHostRunStarted = true;++ process.chdir(input.cwd);+ process.argv = [process.argv[0] ?? process.execPath, BIN, ...input.argv];+ if (!(await nodeVersionGate(input.argv))) return {status: 1, packages: []};++ const {installPlaceOf, projectRootOf} =+ await import('../foundation/release/choose.mjs');+ const {readReleaseFacts} = await import('../foundation/release/project.mjs');+ const {activateHostedRun, recordResolved, resolvedPackages} =+ await import('../foundation/runtime/package-root.mjs');+ const real = fs.realpathSync(CLI_ROOT);+ let projectRoot = null;+ try {+ projectRoot = projectRootOf(readReleaseFacts(input.cwd));+ } catch {+ projectRoot = null;+ }+ activateHostedRun({+ roots: input.roots,+ integrations: input.integrations,+ discoverSources: input.discoverSources,+ // The root that holds this CLI, or, for a CLI that is not installed in a+ // node_modules folder, the folder beside it that holds its Core.+ startingRoot: installPlaceOf(real).owner ?? path.dirname(real),+ projectRoot,+ loadHostEntry,+ });+ recordResolved(+ '@astryxdesign/cli',+ JSON.parse(fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf8'))+ .version,+ CLI_ROOT,+ );++ const {runCli} = await import('../clients/cli/run.mjs');+ const run = () =>+ runCli({+ cliRoot: CLI_ROOT,+ argv: [...input.argv],+ declinedProjectCli: input.declinedProjectCli,+ });+ let answered;+ if (input.cliCommand === undefined) {+ answered = await run();+ } else {+ const {runWithCliDoor} = await import('../foundation/env/cli-command.mjs');+ answered = await runWithCliDoor(input.cliCommand, run);+ }+ // Another package set's host entry answered the run (INV30).+ if (answered) return answered;+ const code = process.exitCode;+ return {+ status: typeof code === 'number' ? code : Number(code ?? 0) || 0,+ packages: resolvedPackages(),+ };+}diff --git a/packages/cli/host/index.test.mjs b/packages/cli/host/index.test.mjsnew file mode 100644index 0000000000..855f82d004--- /dev/null+++ b/packages/cli/host/index.test.mjs@@ -0,0 +1,302 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The host entry, `@astryxdesign/cli/host` (spec AST-081 FR1): every+ * input is checked before anything runs, one run per process, a run matches+ * the bin's, printed commands start with the host's command name, and a+ * project CLI the host declined is never run (FR2, FR9).+ */++import {describe, it, expect, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {+ cleanupFixtures,+ installCore,+ installStandInCli,+ project,+ tempDir,+} from '../test-utils/release-fixtures.mjs';+import {runHostedCli} from './index.mjs';++const HOST = fileURLToPath(new URL('./index.mjs', import.meta.url));+const BIN = fileURLToPath(+ new URL('../clients/cli/bin/astryx.mjs', import.meta.url),+);+const SELF_VERSION = JSON.parse(+ fs.readFileSync(+ fileURLToPath(new URL('../package.json', import.meta.url)),+ 'utf-8',+ ),+).version;++afterEach(cleanupFixtures);++/**+ * A private home and cache, offline, and none of the test runner's package+ * manager or CI settings.+ * @returns {Record<string, string>}+ */+function cleanEnv() {+ const home = tempDir('home');+ const cache = tempDir('cache');+ return {+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ ([key]) => !/^(?:npm_|CI$|NO_UPDATE_NOTIFIER$)/iu.test(key),+ ),+ ),+ HOME: home,+ USERPROFILE: home,+ XDG_CACHE_HOME: cache,+ LOCALAPPDATA: cache,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ APPDATA: path.join(home, 'AppData', 'Roaming'),+ NO_COLOR: '1',+ npm_config_registry: 'http://127.0.0.1:9',+ };+}++/**+ * Start a host process that calls `runHostedCli` with `options` (once, or+ * twice with `{twice: true}`) and exits with the returned status.+ * @param {Record<string, unknown>} options+ * @param {{twice?: boolean, env?: Record<string, string>}} [extra]+ */+function host(options, extra = {}) {+ const script = `+const {runHostedCli} = await import(${JSON.stringify(HOST)});+const options = ${JSON.stringify(options)};+${+ extra.twice+ ? `const first = runHostedCli(options);+try { await runHostedCli(options); } catch (err) { process.stderr.write('second: ' + err.message + '\\n'); }+const {status} = await first;`+ : `const {status} = await runHostedCli(options);`+}+process.exitCode = status;+`;+ const result = spawnSync(+ process.execPath,+ ['--input-type=module', '-e', script],+ {+ cwd: tempDir('host-cwd'),+ encoding: 'utf-8',+ env: extra.env ?? cleanEnv(),+ timeout: 60_000,+ },+ );+ return {status: result.status, stdout: result.stdout, stderr: result.stderr};+}++/**+ * Run the bin itself in `cwd`.+ * @param {string} cwd+ * @param {string[]} args+ * @param {Record<string, string>} env+ */+function bin(cwd, args, env) {+ const result = spawnSync(process.execPath, [BIN, ...args], {+ cwd,+ encoding: 'utf-8',+ env,+ timeout: 60_000,+ });+ return {status: result.status, stdout: result.stdout, stderr: result.stderr};+}++describe('inputs', () => {+ it('rejects every invalid input before running anything', async () => {+ const before = process.cwd();+ const cases = [+ [null, /options must be an object/u],+ [['--version'], /options must be an object/u],+ [{handlers: {}}, /unknown option "handlers"/u],+ [+ {projectCliAlreadyHandled: true},+ /unknown option "projectCliAlreadyHandled"/u,+ ],+ [{roots: '/tmp'}, /roots must be an array of folder paths/u],+ [{roots: ['']}, /roots must be an array of folder paths/u],+ [+ {roots: [path.join(tempDir(), 'missing')]},+ /roots names a path that is not a folder/u,+ ],+ [+ {integrations: 'acme'},+ /integrations must be an array of package names/u,+ ],+ [+ {integrations: ['Acme Widgets']},+ /integrations must be an array of package names/u,+ ],+ [+ {integrations: ['../acme']},+ /integrations must be an array of package names/u,+ ],+ [+ {discoverSources: [{}]},+ /discoverSources must be an array of functions/u,+ ],+ [{argv: '--version'}, /argv must be an array of strings/u],+ [{argv: [1]}, /argv must be an array of strings/u],+ [{cwd: 7}, /cwd must be a folder path/u],+ [{cwd: path.join(tempDir(), 'missing')}, /cwd is not a folder/u],+ [{cliCommand: ''}, /cliCommand/u],+ [{cliCommand: ' acme astryx'}, /cliCommand/u],+ [{cliCommand: 'acme\nastryx'}, /cliCommand/u],+ [{cliCommand: 'a'.repeat(121)}, /cliCommand/u],+ [{cliCommand: 'acme ASTRYX:START'}, /cliCommand/u],+ [+ {declinedProjectCli: ''},+ /declinedProjectCli must be a non-blank single line/u,+ ],+ [+ {declinedProjectCli: 'a\nb'},+ /declinedProjectCli must be a non-blank single line/u,+ ],+ [+ {declinedProjectCli: ' untrusted'},+ /declinedProjectCli must be a non-blank single line/u,+ ],+ [+ {declinedProjectCli: 'x'.repeat(121)},+ /declinedProjectCli must be a non-blank single line/u,+ ],+ [+ {declinedProjectCli: 3},+ /declinedProjectCli must be a non-blank single line/u,+ ],+ ];+ for (const [options, message] of cases) {+ await expect(runHostedCli(/** @type {any} */ (options))).rejects.toThrow(+ message,+ );+ }+ await expect(+ runHostedCli(/** @type {any} */ ({argv: 'x'})),+ ).rejects.toBeInstanceOf(TypeError);+ expect(process.cwd()).toBe(before);+ });+});++describe('one run per process', () => {+ it('fails a second call before it runs anything, and the first run completes', () => {+ const empty = tempDir('empty');+ const result = host({argv: ['--version'], cwd: empty}, {twice: true});+ expect(result.status).toBe(0);+ expect(result.stdout.trim()).toBe(SELF_VERSION);+ expect(result.stderr).toMatch(+ /second: runHostedCli: a run already started in this process/u,+ );+ });+});++describe('a hosted run matches the bin', () => {+ it('gives the same exit status, output, and standard-error line', () => {+ const empty = tempDir('empty');+ const env = cleanEnv();+ for (const args of [+ ['--version'],+ ['component', 'Buttn'],+ ['docs', '--json'],+ ]) {+ const direct = bin(empty, args, env);+ const hosted = host({argv: args, cwd: empty}, {env});+ expect(hosted.status).toBe(direct.status);+ expect(hosted.stdout).toBe(direct.stdout);+ expect(hosted.stderr).toBe(direct.stderr);+ }+ });+});++describe('the command name', () => {+ it('starts the commands help prints with the host name', () => {+ const empty = tempDir('empty');+ const hosted = host({+ argv: ['--help'],+ cwd: empty,+ cliCommand: 'acme astryx',+ });+ expect(hosted.status).toBe(0);+ expect(hosted.stdout).toContain('See acme astryx docs global.');+ const direct = host({argv: ['--help'], cwd: empty});+ expect(direct.stdout).not.toContain('acme astryx');+ });+});++describe('a project CLI the host declined', () => {+ /** A project whose own CLI is a stand-in that reports when it runs. */+ function projectWithCli(version, core = version) {+ const root = project(tempDir(), {+ '@astryxdesign/core': core,+ '@astryxdesign/cli': version,+ });+ installCore(root, core);+ installStandInCli(root, version);+ return root;+ }++ it('without a reason, the run is handed to the project CLI', () => {+ const root = projectWithCli('0.6.8');+ const result = host({argv: ['--version'], cwd: root});+ expect(result.status).toBe(0);+ expect(result.stdout.trim()).toBe('0.6.8');+ });++ it.each(['cannot-start', 'untrusted'])(+ '%s: another release answers itself, with the fallback warning naming the reason',+ reason => {+ const root = projectWithCli('0.6.8');+ const text = host({+ argv: ['--version'],+ cwd: root,+ declinedProjectCli: reason,+ });+ expect(text.status).toBe(0);+ expect(text.stdout.trim()).toBe(SELF_VERSION);+ expect(text.stderr).not.toContain('stand-in');+ expect(text.stderr.trim()).toBe(+ `astryx: could not get Astryx 0.6.8 to match this project's Core (project CLI skipped: ${reason}); answering with CLI ${SELF_VERSION} instead`,+ );+ const json = host({+ argv: ['docs', '--json'],+ cwd: root,+ declinedProjectCli: reason,+ });+ expect(json.status).toBe(0);+ expect(json.stderr).toBe('');+ expect(JSON.parse(json.stdout).meta.answeredBy.copy).toBe('fallback');+ },+ );++ it("the declined CLI's own release answers in its place, named as that CLI's release", () => {+ // The project's CLI is this release while its Core is another, so the+ // answer is the project CLI's release, not the release matched to Core.+ const root = projectWithCli(SELF_VERSION, '0.6.8');+ const json = host({+ argv: ['docs', '--json'],+ cwd: root,+ declinedProjectCli: 'untrusted',+ });+ expect(json.status).toBe(0);+ expect(json.stderr).toBe('');+ expect(JSON.parse(json.stdout).meta.answeredBy).toMatchObject({+ cli: SELF_VERSION,+ core: '0.6.8',+ copy: 'project',+ });+ const text = host({+ argv: ['--version'],+ cwd: root,+ declinedProjectCli: 'untrusted',+ });+ expect(text.status).toBe(0);+ expect(text.stdout.trim()).toBe(SELF_VERSION);+ expect(text.stderr.trim()).toBe(+ `astryx: answered by CLI ${SELF_VERSION}, the release of this project's CLI, in its place (project CLI skipped: untrusted)`,+ );+ });+});diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex fa21ba62cd..38b6ff4993 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -42,6 +42,10 @@"types": "./api/index.d.mts","import": "./api/index.mjs"},+ "./host": {+ "types": "./host/index.d.ts",+ "import": "./host/index.mjs"+ },"./authoring": {"types": "./authoring/index.d.ts","import": "./authoring/index.mjs"@@ -81,6 +85,7 @@"assets","authoring","foundation",+ "host","scripts/postinstall.mjs","CHANGELOG.md"],diff --git a/packages/cli/tsconfig.strict.json b/packages/cli/tsconfig.strict.jsonindex ba65022f80..ff216c6940 100644--- a/packages/cli/tsconfig.strict.json+++ b/packages/cli/tsconfig.strict.json@@ -15,6 +15,8 @@"clients/**/*.ts","foundation/**/*.mjs","foundation/**/*.ts",+ "host/**/*.mjs",+ "host/**/*.ts","lib/**/*.mjs","lib/**/*.ts","utils/**/*.mjs",