An open source design system that's fully customizable and agent ready
TypeScript
refactor(cli): split hook into api/hook leaf shape (#4485)
Joeydfa2565d99c6
diff --git a/.changeset/cli-hook-leaves.md b/.changeset/cli-hook-leaves.mdnew file mode 100644index 0000000000..337e851cf2--- /dev/null+++ b/.changeset/cli-hook-leaves.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[refactor] CLI: hook reorganized into api/hook leaf shape — `hook.mjs` is now a dispatcher+barrel routing to colocated leaves (`list/list.mjs` → hook.list, `detail/detail.mjs` → hook.detail, `detail/params/params.mjs` → hook.detail.params) over a shared `_adapter.mjs` resolver. Pure reorg: `--json` and human output are byte-identical across all modes, and the `hook` export surface (api/index.mjs + CLI) is unchanged.+@josephfarinadiff --git a/packages/cli/api/hook/_adapter.mjs b/packages/cli/api/hook/_adapter.mjsnew file mode 100644index 0000000000..731f92caec--- /dev/null+++ b/packages/cli/api/hook/_adapter.mjs@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Shared resolution + IO for the hook command's leaves.+ *+ * Both the list leaf (hook.list) and the single-hook leaves (hook.detail /+ * hook.detail.params) need to (a) locate @astryxdesign/core and (b) resolve a+ * named hook's authored doc. Those two steps live here so each leaf stays a thin+ * projection over a single shared resolver: the leaves shape the `{type, data}`+ * envelope, this adapter does the "find it on disk" work.+ *+ * @input cwd, hook name+ * @output resolved core dir / loaded HookDoc (or a thrown AstryxError)+ * @position api/hook/_adapter.mjs — shared by ./list, ./detail, ./detail/params+ */++import {findCoreDir} from '../../utils/paths.mjs';+import {findHookDoc, getAllHookNames} from '../../lib/hook-discovery.mjs';+import {loadDocs} from '../../lib/component-loader.mjs';+import {levenshteinDistance} from '../../lib/string-utils.mjs';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../lib/error-codes.mjs';++/**+ * Locate the @astryxdesign/core package directory, or throw the same+ * ERR_CORE_NOT_FOUND envelope the flat command threw. Shared by every hook leaf.+ * @param {string} cwd+ * @returns {string} Absolute path to the core package directory.+ */+export function resolveCoreDir(cwd) {+ const coreDir = findCoreDir(cwd);+ if (!coreDir) {+ throw new AstryxError('Could not find @astryxdesign/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);+ }+ return coreDir;+}++/**+ * Resolve a single hook's authored doc by name, or throw ERR_UNKNOWN_HOOK with+ * fuzzy (levenshtein) suggestions. Shared by the detail and detail.params+ * leaves, which both start from a resolved hook doc.+ * @param {string} coreDir+ * @param {string} name+ * @param {{zh?: boolean, lang?: string|null}} [opts]+ * @returns {Promise<import('../../types/hook').HookDoc>}+ */+export async function resolveHookDoc(coreDir, name, {zh = false, lang = null} = {}) {+ const docPath = findHookDoc(coreDir, name);++ if (!docPath) {+ // Fuzzy search for suggestions+ const allNames = getAllHookNames(coreDir);+ const needle = name.toLowerCase();+ const suggestions = allNames+ .map(hookName => ({+ name: hookName,+ distance: levenshteinDistance(needle, hookName.toLowerCase()),+ }))+ .filter(m => m.distance <= 5)+ .sort((a, b) => a.distance - b.distance)+ .slice(0, 5)+ .map(m => ({name: m.name, reason: `similar name (distance ${m.distance})`}));++ throw new AstryxError(+ `No hook named "${name}"`,+ suggestions,+ ERROR_CODES.ERR_UNKNOWN_HOOK,+ );+ }++ return loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));+}diff --git a/packages/cli/api/hook/detail/detail.mjs b/packages/cli/api/hook/detail/detail.mjsnew file mode 100644index 0000000000..f5cf1208bb--- /dev/null+++ b/packages/cli/api/hook/detail/detail.mjs@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file hook.detail leaf — the full authored doc for one hook.+ *+ * Projects the shared hook resolver (see ../_adapter.mjs) into the+ * `hook.detail` envelope. Byte-for-byte identical to the flat command's+ * single-hook branch.+ *+ * @input hook name + { cwd, zh, lang }+ * @output HookDetailResponse ({ type: 'hook.detail', data: HookDoc })+ * @position api/hook/detail/detail.mjs — dispatched from ../hook.mjs+ */++import {resolveCoreDir, resolveHookDoc} from '../_adapter.mjs';++/**+ * @param {string} name+ * @param {{cwd?: string, zh?: boolean, lang?: string|null}} [options]+ * @returns {Promise<import('../../../types/hook').HookDetailResponse>}+ */+export async function detail(name, {cwd = process.cwd(), zh = false, lang = null} = {}) {+ const coreDir = resolveCoreDir(cwd);+ const docs = await resolveHookDoc(coreDir, name, {zh, lang});+ return {type: 'hook.detail', data: docs};+}diff --git a/packages/cli/api/hook/detail/detail.test.mjs b/packages/cli/api/hook/detail/detail.test.mjsnew file mode 100644index 0000000000..2f75915d8a--- /dev/null+++ b/packages/cli/api/hook/detail/detail.test.mjs@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for the hook.detail leaf, run against the real+ * @astryxdesign/core registry. The list leaf is covered end-to-end by+ * cli/commands/detail-levels.test.mjs; this covers the single-hook detail+ * projection (envelope shape + the ERR_UNKNOWN_HOOK fuzzy-suggestion path).+ */++import {describe, it, expect} from 'vitest';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {detail} from './detail.mjs';++// api/hook/detail/ -> up 5 = repo root (has packages/core, which findCoreDir walks to).+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');++const SLOW = 30_000;++describe('hook.detail leaf', () => {+ it('resolves a real hook into a hook.detail envelope', async () => {+ const res = await detail('useMediaQuery', {cwd: REPO});+ expect(res.type).toBe('hook.detail');+ expect(res.data.name).toBe('useMediaQuery');+ // The full authored doc is projected verbatim, so params/returns arrays exist.+ expect(Array.isArray(res.data.params)).toBe(true);+ expect(Array.isArray(res.data.returns)).toBe(true);+ }, SLOW);++ it('throws ERR_UNKNOWN_HOOK with fuzzy suggestions for an unknown hook', async () => {+ let err;+ try {+ await detail('useNope', {cwd: REPO});+ } catch (e) {+ err = e;+ }+ expect(err).toBeDefined();+ expect(err.code).toBe('ERR_UNKNOWN_HOOK');+ expect(err.message).toBe('No hook named "useNope"');+ expect(Array.isArray(err.suggestions)).toBe(true);+ }, SLOW);+});diff --git a/packages/cli/api/hook/detail/params/params.mjs b/packages/cli/api/hook/detail/params/params.mjsnew file mode 100644index 0000000000..c9672d0545--- /dev/null+++ b/packages/cli/api/hook/detail/params/params.mjs@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file hook.detail.params leaf — the parameters table for one hook.+ *+ * Reuses the shared hook resolver (see ../../_adapter.mjs) and projects just the+ * resolved doc's `params` array into the `hook.detail.params` envelope.+ * Byte-for-byte identical to the flat command's `--params` branch.+ *+ * @input hook name + { cwd, zh, lang }+ * @output HookDetailParamsResponse ({ type: 'hook.detail.params', data: HookParamDoc[] })+ * @position api/hook/detail/params/params.mjs — dispatched from ../../hook.mjs+ */++import {resolveCoreDir, resolveHookDoc} from '../../_adapter.mjs';++/**+ * @param {string} name+ * @param {{cwd?: string, zh?: boolean, lang?: string|null}} [options]+ * @returns {Promise<import('../../../../types/hook').HookDetailParamsResponse>}+ */+export async function params(name, {cwd = process.cwd(), zh = false, lang = null} = {}) {+ const coreDir = resolveCoreDir(cwd);+ const docs = await resolveHookDoc(coreDir, name, {zh, lang});+ return {type: 'hook.detail.params', data: docs.params || []};+}diff --git a/packages/cli/api/hook/detail/params/params.test.mjs b/packages/cli/api/hook/detail/params/params.test.mjsnew file mode 100644index 0000000000..c27b7e68df--- /dev/null+++ b/packages/cli/api/hook/detail/params/params.test.mjs@@ -0,0 +1,39 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for the hook.detail.params leaf, run against the real+ * @astryxdesign/core registry. Covers the params projection (just the resolved+ * doc's params array) and the shared ERR_UNKNOWN_HOOK path.+ */++import {describe, it, expect} from 'vitest';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {params} from './params.mjs';++// api/hook/detail/params/ -> up 6 = repo root (has packages/core).+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../../..');++const SLOW = 30_000;++describe('hook.detail.params leaf', () => {+ it('projects only the params array into a hook.detail.params envelope', async () => {+ const res = await params('useMediaQuery', {cwd: REPO});+ expect(res.type).toBe('hook.detail.params');+ expect(Array.isArray(res.data)).toBe(true);+ // useMediaQuery takes a single `query` string parameter.+ expect(res.data[0].name).toBe('query');+ }, SLOW);++ it('throws ERR_UNKNOWN_HOOK for an unknown hook', async () => {+ let err;+ try {+ await params('useNope', {cwd: REPO});+ } catch (e) {+ err = e;+ }+ expect(err).toBeDefined();+ expect(err.code).toBe('ERR_UNKNOWN_HOOK');+ expect(Array.isArray(err.suggestions)).toBe(true);+ }, SLOW);+});diff --git a/packages/cli/api/hook/hook.mjs b/packages/cli/api/hook/hook.mjsindex 85c3e35e3f..2c4929ff0c 100644--- a/packages/cli/api/hook/hook.mjs+++ b/packages/cli/api/hook/hook.mjs@@ -1,18 +1,22 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Programmatic API for the hook command.+ * @file Programmatic API for the hook command — dispatcher + barrel.*- * Returns the same typed envelope { type, data } that `astryx --json hook` outputs.- * The CLI command handler is a thin wrapper around this function.+ * Returns the same typed envelope { type, data } that `astryx --json hook`+ * outputs. This module is routing only: it computes the shared detail default+ * (kept in sync with the CLI) and dispatches to one of the hook leaves —+ * ./list (hook.list), ./detail (hook.detail), or ./detail/params+ * (hook.detail.params). The CLI command handler is a thin wrapper around this+ * function and api/index.mjs re-exports `hook` from here, so the export surface+ * is unchanged.+ *+ * @position api/hook/hook.mjs — dispatcher over ./list, ./detail, ./detail/params*/-import {findCoreDir} from '../../utils/paths.mjs';-import {discoverHooks, findHookDoc, getAllHookNames} from '../../lib/hook-discovery.mjs';-import {loadDocs} from '../../lib/component-loader.mjs';-import {levenshteinDistance} from '../../lib/string-utils.mjs';-import {AstryxError} from '../error.mjs';-import {ERROR_CODES} from '../../lib/error-codes.mjs';+import {list} from './list/list.mjs';+import {detail as detailLeaf} from './detail/detail.mjs';+import {params as paramsLeaf} from './detail/params/params.mjs';/*** @param {string} [name]@@ -29,9 +33,9 @@ import {ERROR_CODES} from '../../lib/error-codes.mjs';export async function hook(name, options = {}) {const {cwd = process.cwd(),- list = false,+ list: listFlag = false,category,- params = false,+ params: paramsFlag = false,detail: detailOption,lang = null,zh = false,@@ -41,156 +45,18 @@ export async function hook(name, options = {}) {// single-hook views default to 'full', list-style views (--list,// --category, or no name) default to 'brief' (scannable name lists).// Keeping this in sync with the CLI is what the API↔CLI parity test checks.- const isListView = list || category != null || !name;+ const isListView = listFlag || category != null || !name;const detail = detailOption ?? (isListView ? 'brief' : 'full');- const coreDir = findCoreDir(cwd);- if (!coreDir) {- throw new AstryxError('Could not find @astryxdesign/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);- }-// ── List mode ──────────────────────────────────────────────────-- if (category || list || !name) {- const hooks = discoverHooks(coreDir);-- if (category) {- const match = Object.entries(hooks).find(- ([key]) => key.toLowerCase() === category.toLowerCase(),- );- if (!match) {- throw new AstryxError(- `Unknown category "${category}"`,- Object.keys(hooks).map(k => ({name: k, reason: 'valid category'})),- ERROR_CODES.ERR_UNKNOWN_CATEGORY,- );- }-- if (detail === 'compact') {- const entries = [];- for (const hookName of match[1]) {- const docPath = findHookDoc(coreDir, hookName);- if (docPath) {- try {- const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));- entries.push({- name: hookName,- description: docs.usage?.description || '',- import: docs.importPath || '@astryxdesign/core/hooks',- });- } catch {- entries.push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});- }- } else {- entries.push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});- }- }- return {type: 'hook.list', data: {detail: 'compact', components: {[match[0]]: entries}}};- }-- if (detail === 'full') {- const entries = [];- for (const hookName of match[1]) {- const docPath = findHookDoc(coreDir, hookName);- if (docPath) {- try {- entries.push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));- } catch {- entries.push({name: hookName});- }- } else {- entries.push({name: hookName});- }- }- return {type: 'hook.list', data: {detail: 'full', components: {[match[0]]: entries}}};- }-- // Default: names only- return {type: 'hook.list', data: {detail: 'names', components: {[match[0]]: match[1]}}};- }-- // All hooks- if (detail === 'compact') {- /** @type {Record<string, Array<{name: string, description: string, import: string}>>} */- const result = {};- for (const [cat, hookNames] of Object.entries(hooks)) {- result[cat] = [];- for (const hookName of hookNames) {- const docPath = findHookDoc(coreDir, hookName);- if (docPath) {- try {- const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));- result[cat].push({- name: hookName,- description: docs.usage?.description || '',- import: docs.importPath || '@astryxdesign/core/hooks',- });- } catch {- result[cat].push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});- }- } else {- result[cat].push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});- }- }- }- return {type: 'hook.list', data: {detail: 'compact', components: result}};- }-- if (detail === 'full') {- /** @type {Record<string, Array<unknown>>} */- const result = {};- for (const [cat, hookNames] of Object.entries(hooks)) {- result[cat] = [];- for (const hookName of hookNames) {- const docPath = findHookDoc(coreDir, hookName);- if (docPath) {- try {- result[cat].push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));- } catch {- result[cat].push({name: hookName});- }- } else {- result[cat].push({name: hookName});- }- }- }- return {type: 'hook.list', data: {detail: 'full', components: result}};- }-- // Default: names only- return {type: 'hook.list', data: {detail: 'names', components: hooks}};+ if (category || listFlag || !name) {+ return list({cwd, category, detail, zh, lang});}// ── Single hook ────────────────────────────────────────────────-- const docPath = findHookDoc(coreDir, name);-- if (!docPath) {- // Fuzzy search for suggestions- const allNames = getAllHookNames(coreDir);- const needle = name.toLowerCase();- const suggestions = allNames- .map(hookName => ({- name: hookName,- distance: levenshteinDistance(needle, hookName.toLowerCase()),- }))- .filter(m => m.distance <= 5)- .sort((a, b) => a.distance - b.distance)- .slice(0, 5)- .map(m => ({name: m.name, reason: `similar name (distance ${m.distance})`}));-- throw new AstryxError(- `No hook named "${name}"`,- suggestions,- ERROR_CODES.ERR_UNKNOWN_HOOK,- );- }-- const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));-- if (params) {- return {type: 'hook.detail.params', data: docs.params || []};+ if (paramsFlag) {+ return paramsLeaf(name, {cwd, zh, lang});}- return {type: 'hook.detail', data: docs};+ return detailLeaf(name, {cwd, zh, lang});}diff --git a/packages/cli/api/hook/list/list.mjs b/packages/cli/api/hook/list/list.mjsnew file mode 100644index 0000000000..f229a7b7cf--- /dev/null+++ b/packages/cli/api/hook/list/list.mjs@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file hook.list leaf — list hooks grouped by category.+ *+ * Emits ONE `hook.list` type across all three detail levels; the depth is+ * carried in `data.detail` ('names' | 'compact' | 'full') and `data.components`+ * holds the grouped map whose entry shape depends on that level. Byte-for-byte+ * identical to the flat command's list branch.+ *+ * @input { cwd, category?, detail, zh, lang }+ * @output HookListResponse ({ type: 'hook.list', data: { detail, components } })+ * @position api/hook/list/list.mjs — dispatched from ../hook.mjs+ */++import {discoverHooks, findHookDoc} from '../../../lib/hook-discovery.mjs';+import {loadDocs} from '../../../lib/component-loader.mjs';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../lib/error-codes.mjs';+import {resolveCoreDir} from '../_adapter.mjs';++/**+ * @param {object} [options]+ * @param {string} [options.cwd]+ * @param {string} [options.category] - When set, list only this category.+ * @param {'full'|'compact'|'brief'|'names'} [options.detail] - Anything other than 'compact'/'full' renders names only.+ * @param {boolean} [options.zh]+ * @param {string|null} [options.lang]+ * @returns {Promise<import('../../../types/hook').HookListResponse>}+ */+export async function list({cwd = process.cwd(), category, detail = 'names', zh = false, lang = null} = {}) {+ const coreDir = resolveCoreDir(cwd);+ const hooks = discoverHooks(coreDir);++ if (category) {+ const match = Object.entries(hooks).find(+ ([key]) => key.toLowerCase() === category.toLowerCase(),+ );+ if (!match) {+ throw new AstryxError(+ `Unknown category "${category}"`,+ Object.keys(hooks).map(k => ({name: k, reason: 'valid category'})),+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,+ );+ }++ if (detail === 'compact') {+ /** @type {import('../../../types/hook').HookBriefEntry[]} */+ const entries = [];+ for (const hookName of match[1]) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));+ entries.push({+ name: hookName,+ description: docs.usage?.description || '',+ import: docs.importPath || '@astryxdesign/core/hooks',+ });+ } catch {+ entries.push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ }+ } else {+ entries.push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ }+ }+ return {type: 'hook.list', data: {detail: 'compact', components: {[match[0]]: entries}}};+ }++ if (detail === 'full') {+ /** @type {import('../../../types/hook').HookDoc[]} */+ const entries = [];+ for (const hookName of match[1]) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ entries.push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));+ } catch {+ entries.push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));+ }+ } else {+ entries.push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));+ }+ }+ return {type: 'hook.list', data: {detail: 'full', components: {[match[0]]: entries}}};+ }++ // Default: names only+ return {type: 'hook.list', data: {detail: 'names', components: {[match[0]]: match[1]}}};+ }++ // All hooks+ if (detail === 'compact') {+ /** @type {Record<string, import('../../../types/hook').HookBriefEntry[]>} */+ const result = {};+ for (const [cat, hookNames] of Object.entries(hooks)) {+ result[cat] = [];+ for (const hookName of hookNames) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));+ result[cat].push({+ name: hookName,+ description: docs.usage?.description || '',+ import: docs.importPath || '@astryxdesign/core/hooks',+ });+ } catch {+ result[cat].push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ }+ } else {+ result[cat].push({name: hookName, description: '', import: '@astryxdesign/core/hooks'});+ }+ }+ }+ return {type: 'hook.list', data: {detail: 'compact', components: result}};+ }++ if (detail === 'full') {+ /** @type {Record<string, import('../../../types/hook').HookDoc[]>} */+ const result = {};+ for (const [cat, hookNames] of Object.entries(hooks)) {+ result[cat] = [];+ for (const hookName of hookNames) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ result[cat].push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));+ } catch {+ result[cat].push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));+ }+ } else {+ result[cat].push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));+ }+ }+ }+ return {type: 'hook.list', data: {detail: 'full', components: result}};+ }++ // Default: names only+ return {type: 'hook.list', data: {detail: 'names', components: hooks}};+}diff --git a/packages/cli/types/hook.d.ts b/packages/cli/types/hook.d.tsindex 25b794d0b3..41528111e5 100644--- a/packages/cli/types/hook.d.ts+++ b/packages/cli/types/hook.d.ts@@ -22,6 +22,10 @@import type {HookDoc, HookParamDoc} from '../../core/src/docs-types';+// Re-export the authored-doc types the hook leaves project so they stay central+// here (the leaf @returns reference these rather than reaching into core).+export type {HookDoc, HookParamDoc};+/*** xds --json hook [--list] [--category X] [--detail names|compact|full]*