An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): declare every preview-scope module for the playground editor (#6740)
홍규진24af75f8ef64
diff --git a/apps/docsite/scripts/generate-playground-types.mjs b/apps/docsite/scripts/generate-playground-types.mjsindex 09ecfafe7c..d41d480ab1 100644--- a/apps/docsite/scripts/generate-playground-types.mjs+++ b/apps/docsite/scripts/generate-playground-types.mjs@@ -220,8 +220,118 @@ function buildRechartsTypes() {};}+// Lucide ambient module. The installed package's single .d.ts is ~26k lines+// with an SVG preview per icon; bundling it whole would dwarf the rest of the+// payload. Synthesize one declaration from its export list instead, so every+// icon (and every `*Icon` alias) is a named export the editor can resolve —+// an index-signature stub does not give TypeScript any named members, which+// is how `import {Smartphone} from 'lucide-react'` came to be flagged.+function buildLucideTypes() {+ const pkgPath = resolveFromDocsite('lucide-react/package.json');+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));+ const source = readFileSync(+ join(dirname(pkgPath), pkg.types ?? pkg.typings),+ 'utf-8',+ );++ const icons = new Set(+ [+ ...source.matchAll(+ /^declare const (\w+): react\.ForwardRefExoticComponent/gm,+ ),+ ].map(m => m[1]),+ );+ const types = new Set(+ [...source.matchAll(/^(?:type|interface) (\w+)\b/gm)].map(m => m[1]),+ );+ const exportList = source.match(/^export \{([^}]+)\}/m);+ if (!exportList) throw new Error('lucide-react: export list not found');++ const lines = [+ "declare module 'lucide-react' {",+ ' export interface LucideProps {',+ ' size?: string | number;',+ ' color?: string;',+ ' strokeWidth?: string | number;',+ ' absoluteStrokeWidth?: boolean;',+ ' className?: string;',+ ' style?: Record<string, string | number>;',+ ' [attribute: string]: unknown;',+ ' }',+ ' export type LucideIcon = (props: LucideProps) => any;',+ ];+ for (const binding of exportList[1].split(',')) {+ const [local, exported = local] = binding.trim().split(/\s+as\s+/);+ if (!exported || exported === 'LucideProps' || exported === 'LucideIcon') {+ continue;+ }+ if (icons.has(local)) {+ lines.push(` export const ${exported}: LucideIcon;`);+ } else if (types.has(local)) {+ lines.push(` export type ${exported} = any;`);+ } else {+ lines.push(` export const ${exported}: any;`);+ }+ }+ lines.push('}');+ return {'index.d.ts': lines.join('\n')};+}++// Theme packages the preview scope exposes (mirrors SCOPE_THEMES in+// generate-scope.mjs). `astryx theme build` always emits exactly two exports+// from `/built`, typed against @astryxdesign/core, which the editor already+// has. Synthesize the declaration from the table rather than reading the+// package's dist: CI's docsite-test job builds core but not the theme+// packages, so their dist does not exist when this script runs there.+const SCOPE_THEMES = [+ {pkg: '@astryxdesign/theme-neutral', name: 'neutralTheme'},+ {pkg: '@astryxdesign/theme-matcha', name: 'matchaTheme'},+];++function buildThemeTypes() {+ const files = {};+ for (const {pkg, name} of SCOPE_THEMES) {+ const registry = name.replace(/Theme$/, 'IconRegistry');+ files[pkg] = {+ 'index.d.ts':+ `declare module '${pkg}/built' {\n` ++ ` import type {DefinedTheme} from '@astryxdesign/core/theme';\n` ++ ` import type {IconRegistry} from '@astryxdesign/core/Icon';\n` ++ ` export const ${name}: DefinedTheme;\n` ++ ` export const ${registry}: IconRegistry;\n` ++ `}\n` ++ `declare module '${pkg}' {\n export * from '${pkg}/built';\n}`,+ };+ }+ return files;+}++// Runtime-only aliases the scope also serves: `next/image` renders a plain+// <img>, and bare `stylex` is the same object as `@stylexjs/stylex`.+const nextImageTypes = `+declare module 'next/image' {+ const Image: (props: Record<string, unknown>) => any;+ export default Image;+}+`;++const stylexAliasTypes = `+declare module 'stylex' {+ export * from '@stylexjs/stylex';+ export {default} from '@stylexjs/stylex';+}+`;+const heroiconTypes = buildHeroiconTypes();const rechartsTypes = buildRechartsTypes();+const lucideTypes = buildLucideTypes();+const themeTypes = buildThemeTypes();+console.log(+ `Generated Lucide types: ${(lucideTypes['index.d.ts'].match(/: LucideIcon;/g) ?? []).length} icon exports`,+);+console.log(+ `Generated theme types: ${Object.keys(themeTypes).length} packages`,+);console.log(`Generated heroicon types: ${Object.keys(heroiconTypes).length} variants`,);@@ -233,8 +343,12 @@ const output = {'@astryxdesign/core': astryxTypes,react: {'index.d.ts': reactTypes, 'jsx-runtime.d.ts': reactJsxRuntimeTypes},'@stylexjs/stylex': {'index.d.ts': stylexTypes},+ stylex: {'index.d.ts': stylexAliasTypes},'@heroicons/react': heroiconTypes,recharts: rechartsTypes,+ 'lucide-react': lucideTypes,+ 'next/image': {'index.d.ts': nextImageTypes},+ ...themeTypes,};const json = JSON.stringify(output);diff --git a/apps/docsite/src/__tests__/playground-scope.test.ts b/apps/docsite/src/__tests__/playground-scope.test.tsindex 8f4b9f3bd7..a53fec5099 100644--- a/apps/docsite/src/__tests__/playground-scope.test.ts+++ b/apps/docsite/src/__tests__/playground-scope.test.ts@@ -258,6 +258,70 @@ describe('playground-scope', () => {expect(scopeContent).toContain("React.createElement('img', props)");});+ // ── What the editor can type-check ─────────────────────────────────────++ it('declares every module in the preview scope for the editor', () => {+ // The scope says what the preview can require; the types bundle says+ // what Monaco can resolve. They are generated by two scripts, and a+ // module present in one but not the other shows up as a red squiggle on+ // an import that renders fine (lucide-react, the theme packages and+ // next/image all sat in that state). Model the editor's registration:+ // ambient `declare module` blocks resolve by name; core files resolve+ // by path, mounted by monacoSetup at `@astryxdesign/core/<rel>`, so a+ // subpath resolves to `<rel>.d.ts` or `<rel>/index.d.ts`.+ const playgroundTypes: Record<string, Record<string, string>> = JSON.parse(+ fs.readFileSync(PLAYGROUND_TYPES_PATH, 'utf-8'),+ );+ const declared = new Set<string>(['@astryxdesign/core']);+ for (const [pkg, files] of Object.entries(playgroundTypes)) {+ for (const [fileName, content] of Object.entries(files)) {+ if (pkg === '@astryxdesign/core') {+ declared.add(`${pkg}/${fileName.replace(/(\/index)?\.d\.ts$/, '')}`);+ continue;+ }+ for (const match of content.matchAll(/declare module '([^']+)'/g)) {+ declared.add(match[1]);+ }+ }+ }++ // Only the `scope` object's own keys: other top-level consts (the StyleX+ // mock, the theme table) also indent their members by two spaces.+ const scopeBody = scopeContent.slice(+ scopeContent.indexOf('export const scope'),+ );+ const scopeKeys = [+ ...[...scopeBody.matchAll(/^ {2}'([^']+)':/gm)].map(m => m[1]),+ ...[...scopeBody.matchAll(/^ {2}([A-Za-z][\w-]*):/gm)].map(m => m[1]),+ ];+ expect(scopeKeys.length).toBeGreaterThan(100);+ const missing = scopeKeys.filter(key => !declared.has(key)).sort();+ expect(missing).toEqual([]);++ // The path model above is only true while monacoSetup mounts each core+ // file at the package root; mounting index files alone left flat+ // subpaths such as `BaseProps` unreachable.+ expect(fs.readFileSync(MONACO_SETUP_PATH, 'utf-8')).toContain(+ 'file:///node_modules/@astryxdesign/core/${relPath}',+ );+ });++ it('exposes lucide-react icons as named exports in the editor', () => {+ const playgroundTypes = JSON.parse(+ fs.readFileSync(PLAYGROUND_TYPES_PATH, 'utf-8'),+ );+ const lucide = playgroundTypes['lucide-react']['index.d.ts'];+ expect(lucide).toContain("declare module 'lucide-react'");+ // An index-signature stub gives TypeScript no named members, so every+ // `import {Smartphone} from 'lucide-react'` was TS2305. Pin one icon,+ // its `*Icon` alias, and that no such stub is left in monacoSetup.+ expect(lucide).toContain('export const Smartphone: LucideIcon;');+ expect(lucide).toContain('export const SmartphoneIcon: LucideIcon;');+ expect(fs.readFileSync(MONACO_SETUP_PATH, 'utf-8')).not.toContain(+ 'Record<string, React.ComponentType',+ );+ });+// ── What the templates actually import ─────────────────────────────────it('resolves every bare import in the page templates', () => {diff --git a/apps/docsite/src/app/playground/monacoSetup.ts b/apps/docsite/src/app/playground/monacoSetup.tsindex 91b9e93fd4..349f4f56cf 100644--- a/apps/docsite/src/app/playground/monacoSetup.ts+++ b/apps/docsite/src/app/playground/monacoSetup.ts@@ -108,12 +108,6 @@ export function configureMonaco('file:///globals.d.ts',);- // Lucide icons wildcard stub so named imports don't show as errors.- ts.addExtraLib(- `declare module 'lucide-react' { const icons: Record<string, React.ComponentType<{size?: number | string; color?: string; strokeWidth?: number | string; className?: string}>>; export = icons; }`,- 'file:///node_modules/lucide-react/index.d.ts',- );-// Load real type definitions from the pre-built JSON bundlefetch('/playground-types.json').then(r => r.json())@@ -158,6 +152,27 @@ export function configureMonaco(ts.addExtraLib(content, `file:///node_modules/recharts/${fileName}`);}+ // Every other package in the bundle (lucide-react, the theme packages,+ // next/image, the bare `stylex` alias) is an ambient `declare module`,+ // so the file path only has to be unique. Registering them generically+ // keeps the editor in step with whatever generate-playground-types.mjs+ // emits for the preview scope.+ const AMBIENT_HANDLED = new Set([+ 'react',+ '@stylexjs/stylex',+ '@heroicons/react',+ 'recharts',+ '@astryxdesign/core',+ ]);+ for (const [pkg, files] of Object.entries(packages)) {+ if (AMBIENT_HANDLED.has(pkg)) {+ continue;+ }+ for (const [fileName, content] of Object.entries(files)) {+ ts.addExtraLib(content, `file:///node_modules/${pkg}/${fileName}`);+ }+ }+const coreFiles = packages['@astryxdesign/core'] ?? {};const submoduleReexports: string[] = [];@@ -167,13 +182,16 @@ export function configureMonaco(`file:///node_modules/@astryxdesign/core/dist/${relPath}`,);+ // Mount at the package root as well, so every subpath the preview+ // scope serves resolves the way it would from node_modules: a+ // directory through its index.d.ts, a flat file such as+ // `BaseProps` or `theme/tokens.stylex` through its own .d.ts.+ ts.addExtraLib(+ content,+ `file:///node_modules/@astryxdesign/core/${relPath}`,+ );if (relPath.endsWith('/index.d.ts')) {- const moduleName = relPath.replace('/index.d.ts', '');- ts.addExtraLib(- content,- `file:///node_modules/@astryxdesign/core/${moduleName}/index.d.ts`,- );- submoduleReexports.push(moduleName);+ submoduleReexports.push(relPath.replace('/index.d.ts', ''));}}