Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/postcss-api-on-first-use.md
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions packages/cli/api/doctor/theme-checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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} */
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/assets/codemods/parse.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
Expand Down
16 changes: 9 additions & 7 deletions packages/cli/foundation/runtime/lazy-dependencies.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
72 changes: 29 additions & 43 deletions packages/cli/test/lazy-dependencies.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
});

Expand Down Expand Up @@ -136,53 +137,38 @@ 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,
['--input-type=module', '-e', script],
{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);
});
Loading