diff --git a/.changeset/postcss-api-on-first-use.md b/.changeset/postcss-api-on-first-use.md new file mode 100644 index 0000000000000..fd6885ab924f7 --- /dev/null +++ b/.changeset/postcss-api-on-first-use.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[perf] `astryx doctor` starts about 6 to 10 ms sooner, and a first lookup in a project whose integration imports the CLI's API about 15 ms sooner. Doctor's theme checks and the codemods' parser loaded postcss as they loaded, so every importer of the CLI's API loaded it too; they now load it only when they read a stylesheet. Output does not change. + +@josephfarina diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjs index 15f1261e1803f..445e15fbfe841 100644 --- a/packages/cli/api/doctor/theme-checks.mjs +++ b/packages/cli/api/doctor/theme-checks.mjs @@ -9,7 +9,7 @@ import * as path from 'node:path'; import {babelParse as parse} from '../../foundation/runtime/lazy-dependencies.mjs'; -import postcss from 'postcss'; +import {postcss} from '../../foundation/runtime/lazy-dependencies.mjs'; import { collectUnloadedFonts, discoverDoctorThemes, @@ -466,7 +466,7 @@ function fontStylesheetEvidence(css, file, seen = new Set()) { const loaded = new Set(); let external = false; let unread = false; - const root = postcss.parse(css); + const root = postcss().parse(css); root.walkAtRules(atRule => { if (atRule.name.toLowerCase() === 'import') { const spec = [...doctorStylesheetImports(`@import ${atRule.params};`)][0]; @@ -533,7 +533,7 @@ function scopedToTheme(rule, slug) { /** @param {string} css @param {string} slug */ function globalRules(css, slug) { const rules = new Map(); - const root = postcss.parse(css); + const root = postcss().parse(css); root.walkRules(rule => { if (scopedToTheme(rule, slug)) return; /** @type {import('postcss').Node|undefined} */ diff --git a/packages/cli/assets/codemods/parse.mjs b/packages/cli/assets/codemods/parse.mjs index 9f0578b78c46a..a419fa7829c00 100644 --- a/packages/cli/assets/codemods/parse.mjs +++ b/packages/cli/assets/codemods/parse.mjs @@ -12,7 +12,7 @@ * error a codemod throws still fails the run. */ -import postcss from 'postcss'; +import {postcss} from '../../foundation/runtime/lazy-dependencies.mjs'; import {selectorParser as loadSelectorParser} from '../../foundation/runtime/lazy-dependencies.mjs'; export const CODEMOD_PARSE_ERROR = 'ERR_CODEMOD_PARSE'; @@ -45,7 +45,7 @@ export function isCodemodParseError(err) { */ export function parseCss(source, options) { try { - return postcss.parse(source, options); + return postcss().parse(source, options); } catch (err) { throw markParseError(err); } diff --git a/packages/cli/foundation/runtime/lazy-dependencies.mjs b/packages/cli/foundation/runtime/lazy-dependencies.mjs index 479e1f567854a..dd941ab15b6e2 100644 --- a/packages/cli/foundation/runtime/lazy-dependencies.mjs +++ b/packages/cli/foundation/runtime/lazy-dependencies.mjs @@ -71,24 +71,26 @@ export const selectorParser = () => (selectors ??= require('postcss-selector-parser')); /** - * postcss, for modules that `component` and the theme commands load and that - * read a stylesheet only now and then (render/embedded-imports.mjs, - * fonts/font-stylesheet.mjs). Its ES module entry hands on - * what its CommonJS one exports, so this is the one postcss the modules that - * import it get. Not in {@link LAZY_PACKAGES}: those modules import it as - * they load. + * postcss, for the modules that read a stylesheet only now and then: + * doctor's theme checks and the codemods' parser, which the API's import + * path reaches, and the reader of a built theme's imports and the font + * stylesheet reader, which the theme commands load. Its ES module entry hands + * on what its CommonJS one exports, so this is the one postcss the modules + * that import it get. * @returns {typeof import('postcss').default} */ export const postcss = () => (css ??= require('postcss')); /** * Every package loaded on first use, here and in the ShadCN source variants, - * for the test that each resolves to one file either way. + * for the test that each gives one module either way and that importing the + * API loads none of them. */ export const LAZY_PACKAGES = [ '@babel/parser', '@babel/core', 'jscodeshift', + 'postcss', 'postcss-selector-parser', 'recast', '@babel/plugin-transform-typescript', diff --git a/packages/cli/test/lazy-dependencies.test.mjs b/packages/cli/test/lazy-dependencies.test.mjs index e348bd3671e9b..53cb56459b000 100644 --- a/packages/cli/test/lazy-dependencies.test.mjs +++ b/packages/cli/test/lazy-dependencies.test.mjs @@ -4,10 +4,9 @@ * @file lazy-dependencies.test.mjs * @input The heavy dependencies foundation/runtime/lazy-dependencies.mjs * loads on first use, and the public API entry point - * @output Each resolves to the same file for `require` as for `import`, the - * API's exports keep their names and shapes, importing the API loads none - * of those dependencies, and the theme build module, which `component` and - * the theme commands load, loads no postcss + * @output Each gives the same module for `require` as for `import`, the + * API's exports keep their names and shapes, and importing the API loads + * none of those dependencies */ import {spawnSync} from 'node:child_process'; @@ -76,16 +75,18 @@ const API_EXPORTS = { }; describe('lazy dependencies', () => { - it('resolve to the same file for require as for import', () => { + it('give the same module for require as for import', async () => { const require = createRequire( pathToFileURL( path.join(CLI, 'foundation', 'runtime', 'lazy-dependencies.mjs'), ), ); for (const pkg of LAZY_PACKAGES) { - expect(require.resolve(pkg), pkg).toBe( - fileURLToPath(import.meta.resolve(pkg)), - ); + const required = require.resolve(pkg); + if (required === fileURLToPath(import.meta.resolve(pkg))) continue; + // An ES module entry beside the CommonJS one (postcss) must hand on + // what the CommonJS entry exports. + expect(require(pkg), pkg).toBe((await import(pkg)).default); } }); @@ -136,44 +137,29 @@ describe('lazy dependencies', () => { expect(result.stdout, result.stderr).toBe('MODULE_NOT_FOUND'); }, 60_000); - it('give the postcss the other modules import, and leave it unloaded by the theme build module', async () => { - const require = createRequire( - pathToFileURL( - path.join(CLI, 'foundation', 'runtime', 'lazy-dependencies.mjs'), - ), - ); - expect(require('postcss')).toBe((await import('postcss')).default); - const script = ` - import {createRequire} from 'node:module'; - await import(${JSON.stringify( - pathToFileURL(path.join(CLI, 'api', 'theme', 'build', 'build.mjs')) - .href, - )}); - const files = Object.keys(createRequire(import.meta.url).cache); - process.stdout.write( - String(files.some(file => /node_modules[\\\\/]postcss[\\\\/]/.test(file))), - ); - `; - const result = spawnSync( - process.execPath, - ['--input-type=module', '-e', script], - {encoding: 'utf8'}, - ); - expect(result.stdout, result.stderr).toBe('false'); - }, 60_000); - it('are not loaded by importing the API', () => { // Every package here is CommonJS, so a load shows in the require cache // (on every supported Node, unlike module hooks). const script = ` import {createRequire} from 'node:module'; + const scan = () => { + const loaded = new Set(); + for (const file of Object.keys(createRequire(import.meta.url).cache)) { + const m = file.match(/node_modules[\\\\/]((?:@[^\\\\/]+[\\\\/])?[^\\\\/]+)[\\\\/]/g); + if (m) loaded.add(m[m.length - 1].slice(13, -1).replace(/\\\\/g, '/')); + } + return [...loaded]; + }; await import(${JSON.stringify(pathToFileURL(API).href)}); - const loaded = new Set(); - for (const file of Object.keys(createRequire(import.meta.url).cache)) { - const m = file.match(/node_modules[\\\\/]((?:@[^\\\\/]+[\\\\/])?[^\\\\/]+)[\\\\/]/g); - if (m) loaded.add(m[m.length - 1].slice(13, -1).replace(/\\\\/g, '/')); - } - process.stdout.write(JSON.stringify([...loaded])); + const afterApi = scan(); + // One first use, so the scan is shown to see a load. + const lazy = await import(${JSON.stringify( + pathToFileURL( + path.join(CLI, 'foundation', 'runtime', 'lazy-dependencies.mjs'), + ).href, + )}); + lazy.postcss(); + process.stdout.write(JSON.stringify({afterApi, afterUse: scan()})); `; const result = spawnSync( process.execPath, @@ -181,8 +167,8 @@ describe('lazy dependencies', () => { {encoding: 'utf8'}, ); expect(result.status, result.stderr).toBe(0); - const loaded = JSON.parse(result.stdout); - expect(loaded.length).toBeGreaterThan(0); - for (const pkg of LAZY_PACKAGES) expect(loaded).not.toContain(pkg); + const {afterApi, afterUse} = JSON.parse(result.stdout); + expect(afterUse).toContain('postcss'); + for (const pkg of LAZY_PACKAGES) expect(afterApi).not.toContain(pkg); }, 60_000); });