From 87efdc0d6be516476e9b8284aace067a334f6d6b Mon Sep 17 00:00:00 2001 From: Rajratna Dhiwar Date: Wed, 2 Dec 2026 00:26:49 +0530 Subject: [PATCH 1/4] chore(cli): split static descriptor reader from theme-discovery --- .changeset/static-descriptor-split.md | 7 + .../discovery/icon-definition-discovery.mjs | 2 +- .../discovery/icon-set-discovery.mjs | 2 +- .../discovery/static-descriptor.mjs | 511 ++++++++++++++++ .../foundation/discovery/theme-discovery.mjs | 552 +----------------- 5 files changed, 535 insertions(+), 539 deletions(-) create mode 100644 .changeset/static-descriptor-split.md create mode 100644 packages/cli/foundation/discovery/static-descriptor.mjs diff --git a/.changeset/static-descriptor-split.md b/.changeset/static-descriptor-split.md new file mode 100644 index 0000000000000..a00fecf0f6129 --- /dev/null +++ b/.changeset/static-descriptor-split.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[chore] Internal: split `readStaticDescriptorValue`, `isIgnoredThemeEntry`, and helpers from `theme-discovery.mjs` into `static-descriptor.mjs` so `icon-set-discovery.mjs` and `icon-definition-discovery.mjs` do not pull `doc-compiler` into their import graph. + +@Rajratna-D diff --git a/packages/cli/foundation/discovery/icon-definition-discovery.mjs b/packages/cli/foundation/discovery/icon-definition-discovery.mjs index ddc8cb06c488b..47d83152b0b0c 100644 --- a/packages/cli/foundation/discovery/icon-definition-discovery.mjs +++ b/packages/cli/foundation/discovery/icon-definition-discovery.mjs @@ -19,7 +19,7 @@ import * as path from 'node:path'; import {parseIconDefinition} from '../../authoring/doctypes/icon-definition/parse.mjs'; import {CLI_ROOT} from '../fs/paths.mjs'; import {listDirEntries} from '../fs/listing-cache.mjs'; -import {readStaticDescriptorValue} from './theme-discovery.mjs'; +import {readStaticDescriptorValue} from './static-descriptor.mjs'; import {compareText} from '../text/compare-text.mjs'; import {ReplacementAliases} from './replacement-aliases.mjs'; diff --git a/packages/cli/foundation/discovery/icon-set-discovery.mjs b/packages/cli/foundation/discovery/icon-set-discovery.mjs index a3897920351d0..9f36f99019348 100644 --- a/packages/cli/foundation/discovery/icon-set-discovery.mjs +++ b/packages/cli/foundation/discovery/icon-set-discovery.mjs @@ -36,7 +36,7 @@ import { import { isIgnoredThemeEntry, readStaticDescriptorValue, -} from './theme-discovery.mjs'; +} from './static-descriptor.mjs'; import {compareText} from '../text/compare-text.mjs'; /** @typedef {import('../../authoring/doctypes/icon-set/type').IconSetData} IconSetData */ diff --git a/packages/cli/foundation/discovery/static-descriptor.mjs b/packages/cli/foundation/discovery/static-descriptor.mjs new file mode 100644 index 0000000000000..10f4478ddd189 --- /dev/null +++ b/packages/cli/foundation/discovery/static-descriptor.mjs @@ -0,0 +1,511 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file Static descriptor reader and ignored-entry filter, split from + * theme-discovery.mjs so icon-set discovery does not pull doc-compiler + * importers into build-dependency graphs. + */ + +import * as fs from 'node:fs'; +import { + readStore, + storedKey, + STORED_DOCS_FILE, +} from '../doc-compiler/stored-docs.mjs'; +import {fileStamp, recordContentRead} from '../fs/read-record.mjs'; +import {babelParser} from '../runtime/lazy-dependencies.mjs'; + +/** + * Descriptor reads in this process, by path and label, reused while the file + * keeps its stamp (`fileStamp`). + * @type {Map} | {error: unknown}}>} + */ +const descriptorReads = new Map(); + +/** + * @param {any} node + * @returns {any} + */ +function unparenthesized(node) { + let current = node; + while (current?.type === 'ParenthesizedExpression') { + current = current.expression; + } + return current; +} + +/** + * Convert one static literal used by ThemeDoc. + * @param {any} node + * @param {string} label + * @returns {string | boolean} + */ +function staticThemeValue(node, label) { + if (node?.type === 'StringLiteral' || node?.type === 'BooleanLiteral') { + return node.value; + } + throw new Error( + `${label} must use static string and boolean values in its default export.`, + ); +} + +/** + * Convert one static literal of a data descriptor (an icon definition): a + * string, a boolean, or an array or plain object of those. + * @param {any} node + * @param {string} label + * @returns {unknown} + */ +function staticDataValue(node, label) { + if (node?.type === 'StringLiteral' || node?.type === 'BooleanLiteral') { + return node.value; + } + if (node?.type === 'ArrayExpression') { + return node.elements.map((/** @type {any} */ element) => + staticDataValue(unparenthesized(element), label), + ); + } + if (node?.type === 'ObjectExpression') { + return staticObject(node, label, staticDataValue); + } + throw new Error( + `${label} must use static strings, booleans, arrays, and objects in its default export.`, + ); +} + +/** + * A static object literal, every value converted by `convert`. + * @param {any} object + * @param {string} label + * @param {(node: any, label: string) => unknown} convert + * @returns {Record} + */ +function staticObject(object, label, convert) { + /** @type {Record} */ + const value = {}; + for (const property of object.properties) { + if (property.type !== 'ObjectProperty' || property.computed) { + throw new Error(`${label} must contain only static object properties.`); + } + const key = + property.key.type === 'Identifier' + ? property.key.name + : property.key.type === 'StringLiteral' + ? property.key.value + : null; + if (key === null) { + throw new Error(`${label} has an invalid property name.`); + } + if (Object.hasOwn(value, key)) { + throw new Error(`${label} declares "${key}" more than once.`); + } + // Defined, not assigned, so `__proto__` stays a key the parser rejects. + Object.defineProperty(value, key, { + value: convert(unparenthesized(property.value), label), + enumerable: true, + writable: true, + configurable: true, + }); + } + return value; +} + +/** + * The static value a typed descriptor default-exports, read from its source + * without executing it. Throws when the file is not one static object typed + * with `typeName` from `@astryxdesign/cli/authoring`. + * @param {string} docPath + * @param {string} label + * @param {string} typeName the public authoring type, such as `ThemeDoc` + * @param {{data?: boolean}} [options] + * @returns {Record} + */ +export function readStaticDescriptorValue( + docPath, + label, + typeName, + {data = false} = {}, +) { + recordContentRead(docPath); + const stamp = fileStamp(docPath); + if (stamp === '-') fs.statSync(docPath); + const key = `${docPath}\0${label}\0${typeName}\0${data}`; + let cached = descriptorReads.get(key); + if (cached?.stamp !== stamp) { + /** @type {{value: Record} | {error: unknown}} */ + let read; + try { + const source = fs.readFileSync(docPath, 'utf-8'); + let stored; + try { + stored = readStore(STORED_DOCS_FILE).get( + descriptorStoreKey(source, typeName, data), + ); + } catch { + stored = undefined; + } + read = { + value: + stored != null && typeof stored === 'object' + ? stored + : readDescriptorSource(source, label, typeName, data), + }; + } catch (error) { + read = {error}; + } + cached = {stamp, read}; + if (stamp !== '-') descriptorReads.set(key, cached); + } + if ('error' in cached.read) throw cached.read.error; + return data ? structuredClone(cached.read.value) : {...cached.read.value}; +} + +/** + * The typed descriptors read statically, each with whether plain data is + * accepted: what scripts/generate-stored-docs.mjs reads at publish. + * @type {ReadonlyArray<[string, boolean]>} + */ +export const STATIC_DESCRIPTOR_TYPES = [ + ['ThemeDoc', false], + ['IconSetDoc', false], + ['IconDefinitionDoc', true], +]; + +/** + * Where a descriptor's statically read value is stored at publish. + * @param {string} source + * @param {string} typeName + * @param {boolean} data + * @returns {string} + */ +export function descriptorStoreKey(source, typeName, data) { + return `descriptor:${typeName}:${data ? 'data' : 'object'}:${storedKey(source)}`; +} + +/** + * The static value a descriptor's source default-exports. + * @param {string} source + * @param {string} label + * @param {string} typeName + * @param {boolean} [data] + * @returns {Record} + */ +export function readDescriptorSource(source, label, typeName, data = false) { + /** @type {any} */ + let ast; + try { + ast = babelParser().parse(source, { + sourceType: 'module', + tokens: true, + createParenthesizedExpressions: true, + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`${label} could not be parsed: ${message}`, {cause: error}); + } + + const statements = ast.program.body; + const defaults = statements.filter( + (/** @type {any} */ statement) => + statement.type === 'ExportDefaultDeclaration', + ); + const unsupported = statements.filter( + (/** @type {any} */ statement) => + statement.type !== 'ExportDefaultDeclaration' && + statement.type !== 'EmptyStatement', + ); + if (unsupported.length > 0 || ast.program.directives.length > 0) { + throw new Error( + `${label} must contain only its static default-exported ${typeName} object.`, + ); + } + const object = + defaults.length === 1 && unparenthesized(defaults[0].declaration); + if (object?.type !== 'ObjectExpression') { + throw new Error( + `${label} must default-export one static ${typeName} object.`, + ); + } + if (!declaresDocType(ast, defaults[0], typeName)) { + throw new Error( + `${label} must declare its public ${typeName} type from @astryxdesign/cli/authoring.`, + ); + } + + return staticObject(object, label, data ? staticDataValue : staticThemeValue); +} + +/** @param {string} typeName */ +const authoringTypeRe = typeName => + new RegExp( + String.raw`^import\((['"])@astryxdesign\/cli\/authoring\1\)\.${typeName}$`, + 'u', + ); + +/** @param {any} comment */ +function isJsdoc(comment) { + return comment.type === 'CommentBlock' && comment.value.startsWith('*'); +} + +/** @param {string} ch */ +const isSpace = ch => ch === ' ' || ch === '\t'; + +/** + * @param {string} value + * @returns {{name: string, text: string}[]} + */ +function jsdocTags(value) { + const body = value.slice(1); + /** @type {number[]} */ + const starts = []; + let lineStart = true; + let sawAsterisk = true; + let inTag = false; + let backticks = false; + for (let index = 0; index < body.length; index++) { + const ch = body[index]; + if (ch === '\n' || ch === '\r') { + lineStart = true; + sawAsterisk = false; + backticks = false; + continue; + } + if (lineStart) { + if (isSpace(ch)) continue; + if (ch === '*' && !sawAsterisk) { + sawAsterisk = true; + continue; + } + lineStart = false; + if (ch === '@') { + starts.push(index); + inTag = true; + continue; + } + } + if (ch === '`' && inTag) { + backticks = !backticks; + } else if ( + ch === '@' && + !backticks && + isSpace(body[index - 1] ?? '') && + !/\s/u.test(body[index + 1] ?? ' ') + ) { + starts.push(index); + inTag = true; + backticks = false; + } + } + return starts.map((start, position) => { + const raw = body.slice(start + 1, starts[position + 1] ?? body.length); + const name = /^[\w$]*/u.exec(raw)?.[0] ?? ''; + const text = raw.slice(name.length).replace(/(\r?\n)[ \t]*\*?/gu, '$1'); + return {name, text}; + }); +} + +/** + * @param {string} text + * @returns {{type: string, rest: string} | null} + */ +function bracedType(text) { + const open = text.search(/\S/u); + if (open === -1 || text[open] !== '{') return null; + let depth = 0; + /** @type {string | null} */ + let quote = null; + for (let index = open; index < text.length; index++) { + const ch = text[index]; + if (quote) { + if (ch === quote) quote = null; + } else if (ch === "'" || ch === '"' || ch === '`') { + quote = ch; + } else if (ch === '{') { + depth++; + } else if (ch === '}' && --depth === 0) { + return { + type: text.slice(open + 1, index).replace(/\s+/gu, ''), + rest: text.slice(index + 1), + }; + } + } + return null; +} + +/** + * @param {string} type + * @param {string} operator + */ +function splitType(type, operator) { + /** @type {string[]} */ + const parts = []; + let depth = 0; + /** @type {string | null} */ + let quote = null; + let last = 0; + for (let index = 0; index < type.length; index++) { + const ch = type[index]; + if (quote) { + if (ch === quote) quote = null; + } else if (ch === "'" || ch === '"' || ch === '`') { + quote = ch; + } else if ('([{<'.includes(ch)) { + depth++; + } else if (')]}>'.includes(ch)) { + depth--; + } else if (ch === operator && depth === 0) { + parts.push(type.slice(last, index)); + last = index + 1; + } + } + parts.push(type.slice(last)); + return parts; +} + +/** @param {string} type */ +function wrappedInParens(type) { + if (!type.startsWith('(') || !type.endsWith(')')) return false; + let depth = 0; + for (let index = 0; index < type.length; index++) { + if (type[index] === '(') depth++; + else if (type[index] === ')' && --depth === 0) { + return index === type.length - 1; + } + } + return false; +} + +/** + * @param {string} type + * @param {Map} aliases + * @param {string} typeName + * @param {Set} [seen] + * @returns {boolean} + */ +function isDocType(type, aliases, typeName, seen = new Set()) { + let current = type; + for (;;) { + if (/^[!?]/u.test(current)) current = current.slice(1); + else if (current.endsWith('=')) current = current.slice(0, -1); + else if (wrappedInParens(current)) current = current.slice(1, -1); + else break; + } + const members = splitType(current, '|').filter( + member => member !== 'null' && member !== 'undefined', + ); + if (members.length !== 1) return false; + if (members[0] !== current) { + return isDocType(members[0], aliases, typeName, seen); + } + const parts = splitType(current, '&').filter(part => part !== '{}'); + if (parts.length !== 1) return false; + if (parts[0] !== current) return isDocType(parts[0], aliases, typeName, seen); + if (authoringTypeRe(typeName).test(current)) return true; + const named = aliases.get(current); + if (named === undefined || seen.has(current)) return false; + seen.add(current); + return isDocType(named, aliases, typeName, seen); +} + +const AUTHORING = String.raw`(['"])@astryxdesign\/cli\/authoring\2`; + +/** + * @param {any[]} comments + * @param {string} typeName + * @returns {Map} + */ +function jsdocAliases(comments, typeName) { + /** @type {Map} */ + const aliases = new Map(); + const theme = `import('@astryxdesign/cli/authoring').${typeName}`; + for (const comment of comments.filter(isJsdoc)) { + for (const tag of jsdocTags(comment.value)) { + if (tag.name === 'typedef') { + const typed = bracedType(tag.text); + const name = typed && /^\s*([$A-Z_a-z][$\w]*)/u.exec(typed.rest)?.[1]; + if (typed && name) aliases.set(name, typed.type); + } else if (tag.name === 'import') { + const named = new RegExp( + String.raw`^\s*\{([^{}]*)\}\s*from\s*${AUTHORING}`, + 'u', + ).exec(tag.text); + for (const specifier of named?.[1].split(',') ?? []) { + const match = new RegExp( + String.raw`^\s*(?:type\s+)?${typeName}(?:\s+as\s+([$A-Z_a-z][$\w]*))?\s*$`, + 'u', + ).exec(specifier); + if (match) aliases.set(match[1] ?? typeName, theme); + } + const namespace = new RegExp( + String.raw`^\s*\*\s*as\s+([$A-Z_a-z][$\w]*)\s+from\s*${AUTHORING}`, + 'u', + ).exec(tag.text)?.[1]; + if (namespace) aliases.set(`${namespace}.${typeName}`, theme); + } + } + } + return aliases; +} + +/** + * @param {any} ast + * @param {any} exportDefault + * @param {string} typeName + */ +function declaresDocType(ast, exportDefault, typeName) { + const tokens = ast.tokens.filter( + (/** @type {any} */ token) => typeof token.type !== 'string', + ); + const comments = ast.comments ?? []; + /** @param {number} start */ + const jsdocBefore = start => { + const after = + tokens.filter((/** @type {any} */ token) => token.end <= start).at(-1) + ?.end ?? 0; + return comments + .filter( + (/** @type {any} */ comment) => + isJsdoc(comment) && comment.start >= after && comment.end <= start, + ) + .at(-1); + }; + /** @type {Array<{comment: any, tags: string[]}>} */ + const attached = [ + {comment: jsdocBefore(exportDefault.start), tags: ['type']}, + ]; + for ( + let node = exportDefault.declaration; + node.type === 'ParenthesizedExpression'; + node = node.expression + ) { + attached.push({ + comment: jsdocBefore(node.start), + tags: ['type', 'satisfies'], + }); + } + const aliases = jsdocAliases(comments, typeName); + return attached.some(({comment, tags}) => { + if (!comment) return false; + const found = jsdocTags(comment.value); + return tags.some(name => { + const tag = found.find(candidate => candidate.name === name); + const typed = tag && bracedType(tag.text); + return typed != null && isDocType(typed.type, aliases, typeName); + }); + }); +} + +/** + * Whether an entry at any depth of a themes root is outside every theme: a dot + * entry, or a name npm never publishes (npm-packlist's defaults). + * @param {string} name + */ +export function isIgnoredThemeEntry(name) { + return ( + name.startsWith('.') || + name === 'node_modules' || + name === 'CVS' || + name === 'npm-debug.log' || + name.endsWith('.orig') + ); +} diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjs index f7822fc602c9f..0839a5d27613e 100644 --- a/packages/cli/foundation/discovery/theme-discovery.mjs +++ b/packages/cli/foundation/discovery/theme-discovery.mjs @@ -23,21 +23,29 @@ import {lowerDoc} from '../doc-compiler/compile.mjs'; import {packageSource} from '../doc-compiler/source.mjs'; import {CLI_ROOT, realDir} from '../fs/paths.mjs'; import {persistedGather} from '../fs/gather-cache.mjs'; -import {fileStamp, recordContentRead} from '../fs/read-record.mjs'; import {EXACT_CODEC} from '../fs/exact-codec.mjs'; import {listDirEntries} from '../fs/listing-cache.mjs'; import {formatCliCommand} from '../env/package-manager.mjs'; import {LOCAL_THEME_ROOT} from '../config/theme-state.mjs'; import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs'; import {THEME_MODULE_EXTENSIONS} from './theme-module-extensions.mjs'; -import {babelParser, jscodeshift} from '../runtime/lazy-dependencies.mjs'; -import { - readStore, - storedKey, - STORED_DOCS_FILE, -} from '../doc-compiler/stored-docs.mjs'; +import {jscodeshift} from '../runtime/lazy-dependencies.mjs'; import {compareText} from '../text/compare-text.mjs'; import {currentNonCoreBase} from '../bases/state.mjs'; +import { + descriptorStoreKey, + isIgnoredThemeEntry, + readDescriptorSource, + readStaticDescriptorValue, + STATIC_DESCRIPTOR_TYPES, +} from './static-descriptor.mjs'; +export { + descriptorStoreKey, + isIgnoredThemeEntry, + readDescriptorSource, + readStaticDescriptorValue, + STATIC_DESCRIPTOR_TYPES, +}; export const BUNDLED_THEME_PACKAGE = '@astryxdesign/cli'; @@ -555,96 +563,6 @@ function moduleExportsName( return found; } -/** - * An expression without the parentheses around it. - * @param {any} node - * @returns {any} - */ -function unparenthesized(node) { - let current = node; - while (current?.type === 'ParenthesizedExpression') { - current = current.expression; - } - return current; -} - -/** - * Convert one static literal used by ThemeDoc. Theme descriptors intentionally - * contain data only so synchronous bundled-theme APIs stay synchronous. - * @param {any} node - * @param {string} label - * @returns {string | boolean} - */ -function staticThemeValue(node, label) { - if (node?.type === 'StringLiteral' || node?.type === 'BooleanLiteral') { - return node.value; - } - throw new Error( - `${label} must use static string and boolean values in its default export.`, - ); -} - -/** - * Convert one static literal of a data descriptor (an icon definition): a - * string, a boolean, or an array or plain object of those. - * @param {any} node - * @param {string} label - * @returns {unknown} - */ -function staticDataValue(node, label) { - if (node?.type === 'StringLiteral' || node?.type === 'BooleanLiteral') { - return node.value; - } - if (node?.type === 'ArrayExpression') { - return node.elements.map((/** @type {any} */ element) => - staticDataValue(unparenthesized(element), label), - ); - } - if (node?.type === 'ObjectExpression') { - return staticObject(node, label, staticDataValue); - } - throw new Error( - `${label} must use static strings, booleans, arrays, and objects in its default export.`, - ); -} - -/** - * A static object literal, every value converted by `convert`. - * @param {any} object - * @param {string} label - * @param {(node: any, label: string) => unknown} convert - * @returns {Record} - */ -function staticObject(object, label, convert) { - /** @type {Record} */ - const value = {}; - for (const property of object.properties) { - if (property.type !== 'ObjectProperty' || property.computed) { - throw new Error(`${label} must contain only static object properties.`); - } - const key = - property.key.type === 'Identifier' - ? property.key.name - : property.key.type === 'StringLiteral' - ? property.key.value - : null; - if (key === null) { - throw new Error(`${label} has an invalid property name.`); - } - if (Object.hasOwn(value, key)) { - throw new Error(`${label} declares "${key}" more than once.`); - } - // Defined, not assigned, so `__proto__` stays a key the parser rejects. - Object.defineProperty(value, key, { - value: convert(unparenthesized(property.value), label), - enumerable: true, - writable: true, - configurable: true, - }); - } - return value; -} - /** * How messages about a theme descriptor name it. * @param {string} docPath @@ -678,13 +596,6 @@ function readThemeDoc(docPath, owner) { return node.doc; } -/** - * Descriptor reads in this process, by path and label, reused while the file - * keeps its stamp (`fileStamp`). - * @type {Map} | {error: unknown}}>} - */ -const descriptorReads = new Map(); - /** * The static value a theme descriptor default-exports, read from its source * without executing it. Throws when the file is not one static ThemeDoc @@ -697,424 +608,6 @@ export function readThemeDescriptorValue(docPath, label) { return readStaticDescriptorValue(docPath, label, 'ThemeDoc'); } -/** - * The static value a typed descriptor default-exports, read from its source - * without executing it. Throws when the file is not one static object typed - * with `typeName` from `@astryxdesign/cli/authoring`. Theme and icon-set - * descriptors share this reader. - * @param {string} docPath - * @param {string} label - * @param {string} typeName the public authoring type, such as `ThemeDoc` - * @param {{data?: boolean}} [options] `data`: also accept arrays and plain - * objects of static values (icon definitions) - * @returns {Record} - */ -export function readStaticDescriptorValue( - docPath, - label, - typeName, - {data = false} = {}, -) { - // A kept read still counts as a read of the file, so a kept catalog sees an - // edit to it. - recordContentRead(docPath); - const stamp = fileStamp(docPath); - // An absent path throws the error a stat gives. - if (stamp === '-') fs.statSync(docPath); - const key = `${docPath}\0${label}\0${typeName}\0${data}`; - let cached = descriptorReads.get(key); - if (cached?.stamp !== stamp) { - /** @type {{value: Record} | {error: unknown}} */ - let read; - try { - const source = fs.readFileSync(docPath, 'utf-8'); - // A descriptor Astryx ships was read at publish, by the hash of its - // text (scripts/generate-stored-docs.mjs): the same text reads the - // same value without parsing. Any other text, or a store that cannot - // be read, is parsed. - let stored; - try { - stored = readStore(STORED_DOCS_FILE).get( - descriptorStoreKey(source, typeName, data), - ); - } catch { - stored = undefined; - } - read = { - value: - stored != null && typeof stored === 'object' - ? stored - : readDescriptorSource(source, label, typeName, data), - }; - } catch (error) { - read = {error}; - } - cached = {stamp, read}; - // A file that appeared after its stamp is not kept: the entry would - // outlive its removal. - if (stamp !== '-') descriptorReads.set(key, cached); - } - if ('error' in cached.read) throw cached.read.error; - return data ? structuredClone(cached.read.value) : {...cached.read.value}; -} - -/** - * The typed descriptors read statically, each with whether plain data is - * accepted: what scripts/generate-stored-docs.mjs reads at publish. - * @type {ReadonlyArray<[string, boolean]>} - */ -export const STATIC_DESCRIPTOR_TYPES = [ - ['ThemeDoc', false], - ['IconSetDoc', false], - ['IconDefinitionDoc', true], -]; - -/** - * Where a descriptor's statically read value is stored at publish: by the - * hash of its text, the type it is read as, and whether plain data counts. - * @param {string} source - * @param {string} typeName - * @param {boolean} data - * @returns {string} - */ -export function descriptorStoreKey(source, typeName, data) { - return `descriptor:${typeName}:${data ? 'data' : 'object'}:${storedKey(source)}`; -} - -/** - * The static value a descriptor's source default-exports (see - * {@link readStaticDescriptorValue}); throws when it is not one. - * @param {string} source - * @param {string} label - * @param {string} typeName - * @param {boolean} [data] - * @returns {Record} - */ -export function readDescriptorSource(source, label, typeName, data = false) { - /** @type {any} */ - let ast; - try { - ast = babelParser().parse(source, { - sourceType: 'module', - tokens: true, - createParenthesizedExpressions: true, - }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - throw new Error(`${label} could not be parsed: ${message}`, {cause: error}); - } - - const statements = ast.program.body; - const defaults = statements.filter( - (/** @type {any} */ statement) => - statement.type === 'ExportDefaultDeclaration', - ); - const unsupported = statements.filter( - (/** @type {any} */ statement) => - statement.type !== 'ExportDefaultDeclaration' && - statement.type !== 'EmptyStatement', - ); - if (unsupported.length > 0 || ast.program.directives.length > 0) { - throw new Error( - `${label} must contain only its static default-exported ${typeName} object.`, - ); - } - const object = - defaults.length === 1 && unparenthesized(defaults[0].declaration); - if (object?.type !== 'ObjectExpression') { - throw new Error( - `${label} must default-export one static ${typeName} object.`, - ); - } - if (!declaresDocType(ast, defaults[0], typeName)) { - throw new Error( - `${label} must declare its public ${typeName} type from @astryxdesign/cli/authoring.`, - ); - } - - return staticObject(object, label, data ? staticDataValue : staticThemeValue); -} - -/** - * `import('@astryxdesign/cli/authoring').`, without whitespace. - * @param {string} typeName - */ -const authoringTypeRe = typeName => - new RegExp( - String.raw`^import\((['"])@astryxdesign\/cli\/authoring\1\)\.${typeName}$`, - 'u', - ); - -/** @param {any} comment */ -function isJsdoc(comment) { - return comment.type === 'CommentBlock' && comment.value.startsWith('*'); -} - -/** @param {string} ch */ -const isSpace = ch => ch === ' ' || ch === '\t'; - -/** - * The tags of one JSDoc comment, found the way TypeScript's JSDoc scanner - * finds them: an `@` starts a tag at the start of a line (after the margin - * `*`), or after a space and before a non-space, never inside a backtick span - * of a tag's text. Each tag's text runs to the next tag, margins removed. - * @param {string} value the comment's body, as Babel gives it - * @returns {{name: string, text: string}[]} - */ -function jsdocTags(value) { - const body = value.slice(1); - /** @type {number[]} */ - const starts = []; - let lineStart = true; - let sawAsterisk = true; - let inTag = false; - let backticks = false; - for (let index = 0; index < body.length; index++) { - const ch = body[index]; - if (ch === '\n' || ch === '\r') { - lineStart = true; - sawAsterisk = false; - backticks = false; - continue; - } - if (lineStart) { - if (isSpace(ch)) continue; - if (ch === '*' && !sawAsterisk) { - sawAsterisk = true; - continue; - } - lineStart = false; - if (ch === '@') { - starts.push(index); - inTag = true; - continue; - } - } - if (ch === '`' && inTag) { - backticks = !backticks; - } else if ( - ch === '@' && - !backticks && - isSpace(body[index - 1] ?? '') && - !/\s/u.test(body[index + 1] ?? ' ') - ) { - starts.push(index); - inTag = true; - backticks = false; - } - } - return starts.map((start, position) => { - const raw = body.slice(start + 1, starts[position + 1] ?? body.length); - const name = /^[\w$]*/u.exec(raw)?.[0] ?? ''; - const text = raw.slice(name.length).replace(/(\r?\n)[ \t]*\*?/gu, '$1'); - return {name, text}; - }); -} - -/** - * The braced type at the start of a tag's text, and what follows it. - * @param {string} text - * @returns {{type: string, rest: string} | null} - */ -function bracedType(text) { - const open = text.search(/\S/u); - if (open === -1 || text[open] !== '{') return null; - let depth = 0; - /** @type {string | null} */ - let quote = null; - for (let index = open; index < text.length; index++) { - const ch = text[index]; - if (quote) { - if (ch === quote) quote = null; - } else if (ch === "'" || ch === '"' || ch === '`') { - quote = ch; - } else if (ch === '{') { - depth++; - } else if (ch === '}' && --depth === 0) { - return { - type: text.slice(open + 1, index).replace(/\s+/gu, ''), - rest: text.slice(index + 1), - }; - } - } - return null; -} - -/** - * Split a type at top-level occurrences of one operator. - * @param {string} type - * @param {string} operator - */ -function splitType(type, operator) { - /** @type {string[]} */ - const parts = []; - let depth = 0; - /** @type {string | null} */ - let quote = null; - let last = 0; - for (let index = 0; index < type.length; index++) { - const ch = type[index]; - if (quote) { - if (ch === quote) quote = null; - } else if (ch === "'" || ch === '"' || ch === '`') { - quote = ch; - } else if ('([{<'.includes(ch)) { - depth++; - } else if (')]}>'.includes(ch)) { - depth--; - } else if (ch === operator && depth === 0) { - parts.push(type.slice(last, index)); - last = index + 1; - } - } - parts.push(type.slice(last)); - return parts; -} - -/** @param {string} type */ -function wrappedInParens(type) { - if (!type.startsWith('(') || !type.endsWith(')')) return false; - let depth = 0; - for (let index = 0; index < type.length; index++) { - if (type[index] === '(') depth++; - else if (type[index] === ')' && --depth === 0) { - return index === type.length - 1; - } - } - return false; -} - -/** - * Whether a JSDoc type, whitespace removed, checks an object literal exactly - * as `typeName` does: the type or one of its aliases, optionally - * parenthesized, marked `!`, `?` or `=`, joined with `null` or `undefined`, or - * intersected with `{}`. - * @param {string} type - * @param {Map} aliases alias name to the type it names - * @param {string} typeName - * @param {Set} [seen] - * @returns {boolean} - */ -function isDocType(type, aliases, typeName, seen = new Set()) { - let current = type; - for (;;) { - if (/^[!?]/u.test(current)) current = current.slice(1); - else if (current.endsWith('=')) current = current.slice(0, -1); - else if (wrappedInParens(current)) current = current.slice(1, -1); - else break; - } - const members = splitType(current, '|').filter( - member => member !== 'null' && member !== 'undefined', - ); - if (members.length !== 1) return false; - if (members[0] !== current) { - return isDocType(members[0], aliases, typeName, seen); - } - const parts = splitType(current, '&').filter(part => part !== '{}'); - if (parts.length !== 1) return false; - if (parts[0] !== current) return isDocType(parts[0], aliases, typeName, seen); - if (authoringTypeRe(typeName).test(current)) return true; - const named = aliases.get(current); - if (named === undefined || seen.has(current)) return false; - seen.add(current); - return isDocType(named, aliases, typeName, seen); -} - -const AUTHORING = String.raw`(['"])@astryxdesign\/cli\/authoring\2`; - -/** - * The type names the file's JSDoc binds with `@typedef` or `@import`, from any - * JSDoc comment in the module, as TypeScript reads them. - * @param {any[]} comments - * @param {string} typeName - * @returns {Map} - */ -function jsdocAliases(comments, typeName) { - /** @type {Map} */ - const aliases = new Map(); - const theme = `import('@astryxdesign/cli/authoring').${typeName}`; - for (const comment of comments.filter(isJsdoc)) { - for (const tag of jsdocTags(comment.value)) { - if (tag.name === 'typedef') { - const typed = bracedType(tag.text); - const name = typed && /^\s*([$A-Z_a-z][$\w]*)/u.exec(typed.rest)?.[1]; - if (typed && name) aliases.set(name, typed.type); - } else if (tag.name === 'import') { - const named = new RegExp( - String.raw`^\s*\{([^{}]*)\}\s*from\s*${AUTHORING}`, - 'u', - ).exec(tag.text); - for (const specifier of named?.[1].split(',') ?? []) { - const match = new RegExp( - String.raw`^\s*(?:type\s+)?${typeName}(?:\s+as\s+([$A-Z_a-z][$\w]*))?\s*$`, - 'u', - ).exec(specifier); - if (match) aliases.set(match[1] ?? typeName, theme); - } - const namespace = new RegExp( - String.raw`^\s*\*\s*as\s+([$A-Z_a-z][$\w]*)\s+from\s*${AUTHORING}`, - 'u', - ).exec(tag.text)?.[1]; - if (namespace) aliases.set(`${namespace}.${typeName}`, theme); - } - } - } - return aliases; -} - -/** - * Whether the JSDoc TypeScript reads for the default export types it as the - * public `typeName` (such as ThemeDoc): `@type` in the last JSDoc comment between the previous - * token and `export`, or `@type` or `@satisfies` in the last one between the - * previous token and the opening parenthesis of a JSDoc cast of the object. - * Line comments, strings, code spans, and JSDoc anywhere else never type it. - * @param {any} ast parsed with tokens and parenthesized expressions - * @param {any} exportDefault - * @param {string} typeName - */ -function declaresDocType(ast, exportDefault, typeName) { - const tokens = ast.tokens.filter( - (/** @type {any} */ token) => typeof token.type !== 'string', - ); - const comments = ast.comments ?? []; - /** @param {number} start */ - const jsdocBefore = start => { - const after = - tokens.filter((/** @type {any} */ token) => token.end <= start).at(-1) - ?.end ?? 0; - return comments - .filter( - (/** @type {any} */ comment) => - isJsdoc(comment) && comment.start >= after && comment.end <= start, - ) - .at(-1); - }; - /** @type {Array<{comment: any, tags: string[]}>} */ - const attached = [ - {comment: jsdocBefore(exportDefault.start), tags: ['type']}, - ]; - for ( - let node = exportDefault.declaration; - node.type === 'ParenthesizedExpression'; - node = node.expression - ) { - attached.push({ - comment: jsdocBefore(node.start), - tags: ['type', 'satisfies'], - }); - } - const aliases = jsdocAliases(comments, typeName); - return attached.some(({comment, tags}) => { - if (!comment) return false; - const found = jsdocTags(comment.value); - return tags.some(name => { - const tag = found.find(candidate => candidate.name === name); - const typed = tag && bracedType(tag.text); - return typed != null && isDocType(typed.type, aliases, typeName); - }); - }); -} - /** * Whether a file is the module `astryx theme build` writes rather than a * theme source: plain JavaScript that carries the build's generated header @@ -1238,21 +731,6 @@ function confirmedThemeSource(sourceDir, built, slug, files) { /** A module named for the theme it exports, such as `oceanTheme.ts`. */ const THEME_SOURCE_RE = /^[$A-Z_a-z][$\w]*Theme\.(?:mjs|js|mts|ts|tsx|jsx)$/u; -/** - * Whether an entry at any depth of a themes root is outside every theme: a dot - * entry, or a name npm never publishes (npm-packlist's defaults). - * @param {string} name - */ -export function isIgnoredThemeEntry(name) { - return ( - name.startsWith('.') || - name === 'node_modules' || - name === 'CVS' || - name === 'npm-debug.log' || - name.endsWith('.orig') - ); -} - /** * Every entry below one folder of a theme root, without following symlinks * and without {@link isIgnoredThemeEntry} entries. From a24b55fb5c7d997092535baf0ace42f07200da33 Mon Sep 17 00:00:00 2001 From: Rajratna Dhiwar Date: Wed, 2 Dec 2026 10:14:17 +0530 Subject: [PATCH 2/4] chore(cli): clarify changeset import graph and restore descriptor comments --- .changeset/static-descriptor-split.md | 2 +- .../discovery/static-descriptor.mjs | 37 ++++++++++++++++--- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/.changeset/static-descriptor-split.md b/.changeset/static-descriptor-split.md index a00fecf0f6129..bf6ef9baf2a5e 100644 --- a/.changeset/static-descriptor-split.md +++ b/.changeset/static-descriptor-split.md @@ -2,6 +2,6 @@ '@astryxdesign/cli': patch --- -[chore] Internal: split `readStaticDescriptorValue`, `isIgnoredThemeEntry`, and helpers from `theme-discovery.mjs` into `static-descriptor.mjs` so `icon-set-discovery.mjs` and `icon-definition-discovery.mjs` do not pull `doc-compiler` into their import graph. +[chore] Internal: split `readStaticDescriptorValue`, `isIgnoredThemeEntry`, and helpers from `theme-discovery.mjs` into `static-descriptor.mjs` so `icon-set-discovery.mjs` and `icon-definition-discovery.mjs` no longer import `doc-compiler/compile.mjs`, whose graph reaches the dynamic `import(url)` in `fs/import-url.mjs`. @Rajratna-D diff --git a/packages/cli/foundation/discovery/static-descriptor.mjs b/packages/cli/foundation/discovery/static-descriptor.mjs index 10f4478ddd189..4f1767e0060e2 100644 --- a/packages/cli/foundation/discovery/static-descriptor.mjs +++ b/packages/cli/foundation/discovery/static-descriptor.mjs @@ -2,8 +2,13 @@ /** * @file Static descriptor reader and ignored-entry filter, split from - * theme-discovery.mjs so icon-set discovery does not pull doc-compiler - * importers into build-dependency graphs. + * theme-discovery.mjs so icon-set discovery does not pull doc-compiler/compile.mjs + * (and fs/import-url.mjs) into build-dependency graphs. + * + * @input Descriptor file paths, source strings, and public authoring type names + * @output Statically parsed descriptor values, store keys, and directory entry + * ignore predicate + * @position packages/cli/foundation/discovery — static descriptor reader */ import * as fs from 'node:fs'; @@ -126,8 +131,11 @@ export function readStaticDescriptorValue( typeName, {data = false} = {}, ) { + // A kept read still counts as a read of the file, so a kept catalog sees an + // edit to it. recordContentRead(docPath); const stamp = fileStamp(docPath); + // An absent path throws the error a stat gives. if (stamp === '-') fs.statSync(docPath); const key = `${docPath}\0${label}\0${typeName}\0${data}`; let cached = descriptorReads.get(key); @@ -136,6 +144,10 @@ export function readStaticDescriptorValue( let read; try { const source = fs.readFileSync(docPath, 'utf-8'); + // A descriptor Astryx ships was read at publish, by the hash of its + // text (scripts/generate-stored-docs.mjs): the same text reads the + // same value without parsing. Any other text, or a store that cannot + // be read, is parsed. let stored; try { stored = readStore(STORED_DOCS_FILE).get( @@ -154,6 +166,8 @@ export function readStaticDescriptorValue( read = {error}; } cached = {stamp, read}; + // A file that appeared after its stamp is not kept: the entry would + // outlive its removal. if (stamp !== '-') descriptorReads.set(key, cached); } if ('error' in cached.read) throw cached.read.error; @@ -251,7 +265,11 @@ function isJsdoc(comment) { const isSpace = ch => ch === ' ' || ch === '\t'; /** - * @param {string} value + * The tags of one JSDoc comment, found the way TypeScript's JSDoc scanner + * finds them: an `@` starts a tag at the start of a line (after the margin + * `*`), or after a space and before a non-space, never inside a backtick span + * of a tag's text. Each tag's text runs to the next tag, margins removed. + * @param {string} value the comment's body, as Babel gives it * @returns {{name: string, text: string}[]} */ function jsdocTags(value) { @@ -376,8 +394,12 @@ function wrappedInParens(type) { } /** + * Whether a JSDoc type, whitespace removed, checks an object literal exactly + * as `typeName` does: the type or one of its aliases, optionally + * parenthesized, marked `!`, `?` or `=`, joined with `null` or `undefined`, or + * intersected with `{}`. * @param {string} type - * @param {Map} aliases + * @param {Map} aliases alias name to the type it names * @param {string} typeName * @param {Set} [seen] * @returns {boolean} @@ -448,7 +470,12 @@ function jsdocAliases(comments, typeName) { } /** - * @param {any} ast + * Whether the JSDoc TypeScript reads for the default export types it as the + * public `typeName` (such as ThemeDoc): `@type` in the last JSDoc comment between the previous + * token and `export`, or `@type` or `@satisfies` in the last one between the + * previous token and the opening parenthesis of a JSDoc cast of the object. + * Line comments, strings, code spans, and JSDoc anywhere else never type it. + * @param {any} ast parsed with tokens and parenthesized expressions * @param {any} exportDefault * @param {string} typeName */ From 47e7b50e2f80c4413c185aa77f5cf9367fd348e6 Mon Sep 17 00:00:00 2001 From: Rajratna Dhiwar Date: Thu, 3 Dec 2026 20:51:44 +0530 Subject: [PATCH 3/4] chore(cli): restore remaining JSDoc notes and update generate-stored-docs comment --- packages/cli/foundation/discovery/static-descriptor.mjs | 9 ++++++--- packages/cli/scripts/generate-stored-docs.mjs | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/cli/foundation/discovery/static-descriptor.mjs b/packages/cli/foundation/discovery/static-descriptor.mjs index 4f1767e0060e2..bb855fc7b5c2e 100644 --- a/packages/cli/foundation/discovery/static-descriptor.mjs +++ b/packages/cli/foundation/discovery/static-descriptor.mjs @@ -40,7 +40,8 @@ function unparenthesized(node) { } /** - * Convert one static literal used by ThemeDoc. + * Convert one static literal used by ThemeDoc. Theme descriptors intentionally + * contain data only so synchronous bundled-theme APIs stay synchronous. * @param {any} node * @param {string} label * @returns {string | boolean} @@ -118,11 +119,13 @@ function staticObject(object, label, convert) { /** * The static value a typed descriptor default-exports, read from its source * without executing it. Throws when the file is not one static object typed - * with `typeName` from `@astryxdesign/cli/authoring`. + * with `typeName` from `@astryxdesign/cli/authoring`. Theme and icon-set + * descriptors share this reader. * @param {string} docPath * @param {string} label * @param {string} typeName the public authoring type, such as `ThemeDoc` - * @param {{data?: boolean}} [options] + * @param {{data?: boolean}} [options] `data`: also accept arrays and plain + * objects of static values (icon definitions) * @returns {Record} */ export function readStaticDescriptorValue( diff --git a/packages/cli/scripts/generate-stored-docs.mjs b/packages/cli/scripts/generate-stored-docs.mjs index 7a5a009682210..f1755b95d1429 100644 --- a/packages/cli/scripts/generate-stored-docs.mjs +++ b/packages/cli/scripts/generate-stored-docs.mjs @@ -183,7 +183,7 @@ export async function storedDocsText() { for (const file of files) { const text = fs.readFileSync(file, 'utf-8'); // Each typed descriptor's statically read value, which the published - // package reads instead of parsing the file (theme-discovery.mjs). + // package reads instead of parsing the file (static-descriptor.mjs). for (const [typeName, asData] of STATIC_DESCRIPTOR_TYPES) { if (!text.includes(typeName)) continue; let value; From a68dbf4a7f83772c8aee692054c851a7c91faf43 Mon Sep 17 00:00:00 2001 From: Rajratna Dhiwar Date: Thu, 3 Dec 2026 21:42:27 +0530 Subject: [PATCH 4/4] chore(cli): restore remaining JSDoc summaries in static-descriptor.mjs --- .../cli/foundation/discovery/static-descriptor.mjs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/cli/foundation/discovery/static-descriptor.mjs b/packages/cli/foundation/discovery/static-descriptor.mjs index bb855fc7b5c2e..0c1a2e16fd8b9 100644 --- a/packages/cli/foundation/discovery/static-descriptor.mjs +++ b/packages/cli/foundation/discovery/static-descriptor.mjs @@ -189,7 +189,8 @@ export const STATIC_DESCRIPTOR_TYPES = [ ]; /** - * Where a descriptor's statically read value is stored at publish. + * Where a descriptor's statically read value is stored at publish: by the + * hash of its text, the type it is read as, and whether plain data counts. * @param {string} source * @param {string} typeName * @param {boolean} data @@ -200,7 +201,8 @@ export function descriptorStoreKey(source, typeName, data) { } /** - * The static value a descriptor's source default-exports. + * The static value a descriptor's source default-exports (see + * {@link readStaticDescriptorValue}); throws when it is not one. * @param {string} source * @param {string} label * @param {string} typeName @@ -252,7 +254,10 @@ export function readDescriptorSource(source, label, typeName, data = false) { return staticObject(object, label, data ? staticDataValue : staticThemeValue); } -/** @param {string} typeName */ +/** + * `import('@astryxdesign/cli/authoring').`, without whitespace. + * @param {string} typeName + */ const authoringTypeRe = typeName => new RegExp( String.raw`^import\((['"])@astryxdesign\/cli\/authoring\1\)\.${typeName}$`, @@ -435,6 +440,8 @@ function isDocType(type, aliases, typeName, seen = new Set()) { const AUTHORING = String.raw`(['"])@astryxdesign\/cli\/authoring\2`; /** + * The type names the file's JSDoc binds with `@typedef` or `@import`, from any + * JSDoc comment in the module, as TypeScript reads them. * @param {any[]} comments * @param {string} typeName * @returns {Map}