diff --git a/BREAKING_CHANGES.md b/BREAKING_CHANGES.md index 6a01fac3d59..d326bbc65ab 100644 --- a/BREAKING_CHANGES.md +++ b/BREAKING_CHANGES.md @@ -31,6 +31,7 @@ Stencil recently had its 10th birthday - this release is a consolidation, organi - [Shadow Roots of Parser-Created Elements Attach on Connect](#shadow-roots-of-parser-created-elements-attach-on-connect) - [Boolean Props: `"false"` Is Now `true`](#boolean-props-false-is-now-true) - [Rollup Replaced with Rolldown](#rollup-replaced-with-rolldown) + - [CSS Autoprefixing and Minification Use Lightning CSS](#css-autoprefixing-and-minification-use-lightning-css) - [JSX Types](#jsx-types) - [`extras` Renamed to `compat`](#extras-renamed-to-compat) - [Collection Importing / Re-bundling](#collection-importing--re-bundling) @@ -263,6 +264,10 @@ Rollup has been replaced with [Rolldown](https://rolldown.rs/) as Stencil's bund To migrate, run `stencil migrate` to rename these fields automatically. A number of previously supported Rollup options have no Rolldown equivalent and will be removed; others have new names and will be renamed. If you reference Rollup types or internals directly, check the [Rolldown documentation](https://rolldown.rs/) for the closest equivalent. +#### CSS Autoprefixing and Minification Use Lightning CSS + +Autoprefixing (`autoprefixCss`) and CSS minification (`minifyCss`) now run through [Lightning CSS](https://lightningcss.dev/) instead of Autoprefixer and Stencil's own minifier. Lightning CSS parses selectors strictly, so CSS that was previously passed through untouched may now fail the build. The most common case is a pseudo-class placed after a pseudo-element, e.g. `.foo::before:dir(rtl)` (often generated by Sass nesting such as an RTL mixin included inside `&::before`). Move the pseudo-class before the pseudo-element: `.foo:dir(rtl)::before`. + #### JSX Types `JSX.Element` was previously left undefined in the `h` namespace, which caused TypeScript to silently fall back to `any` for JSX expressions (surfacing as `no-unsafe-return` errors under strict `@typescript-eslint` configs). Three related type-level changes: diff --git a/packages/core/src/compiler/config/_test_/validate-package-json.spec.ts b/packages/core/src/compiler/config/_test_/validate-package-json.spec.ts index 6366e7eea81..b2c259ca5c0 100644 --- a/packages/core/src/compiler/config/_test_/validate-package-json.spec.ts +++ b/packages/core/src/compiler/config/_test_/validate-package-json.spec.ts @@ -607,6 +607,19 @@ describe('validateBuildPackageJson', () => { expect(filesWarning).toBeUndefined(); }); + it('should error when a "files" entry does not exist on disk', async () => { + compilerCtx.fs.access = async (p: string) => !p.endsWith('missing.js'); + buildCtx.packageJson.files = ['dist', 'missing.js']; + + await validateBuildPackageJson(config, compilerCtx, buildCtx); + + const filesError = buildCtx.diagnostics.find((d) => d.messageText.includes('missing.js')); + expect(filesError?.level).toBe('error'); + expect(filesError?.messageText).toBe( + '"missing.js" is listed in the package.json "files" array but could not be found on disk.', + ); + }); + it('should warn when "files" does not cover the Custom Elements Manifest', async () => { compilerCtx.fs.access = async () => true; config.outputTargets.push({ diff --git a/packages/core/src/compiler/config/validate-package-json.ts b/packages/core/src/compiler/config/validate-package-json.ts index f97037e36a6..0b2d1a5214e 100644 --- a/packages/core/src/compiler/config/validate-package-json.ts +++ b/packages/core/src/compiler/config/validate-package-json.ts @@ -580,7 +580,7 @@ const validateFilesField = async ( const hasAccess = await compilerCtx.fs.access(absPath); if (!hasAccess) { - const msg = `Unable to find "${pkgFile}" within the package.json "files" array.`; + const msg = `"${pkgFile}" is listed in the package.json "files" array but could not be found on disk.`; packageJsonError(config, compilerCtx, buildCtx, msg, `"${pkgFile}"`); } } diff --git a/packages/core/src/compiler/optimize/_test_/autoprefixer.spec.ts b/packages/core/src/compiler/optimize/_test_/autoprefixer.spec.ts new file mode 100644 index 00000000000..5df8807188c --- /dev/null +++ b/packages/core/src/compiler/optimize/_test_/autoprefixer.spec.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; + +import { autoprefixCss } from '../autoprefixer'; + +describe('autoprefixCss', () => { + it('names the selector for a pseudo-class after a pseudo-element', async () => { + const css = `.a { color: red; }\n.b::before:dir(rtl) { left: unset; }`; + const { diagnostics } = await autoprefixCss(css, null, '/src/cmp.css'); + + expect(diagnostics).toHaveLength(1); + expect(diagnostics[0].messageText).toBe( + `Invalid CSS selector ".b::before:dir(rtl)": Invalid state. A pseudo-class can't follow a pseudo-element (e.g. \`::before:dir(rtl)\`); move it before (\`:dir(rtl)::before\`).`, + ); + expect(diagnostics[0].absFilePath).toBe('/src/cmp.css'); + expect(diagnostics[0].lineNumber).toBe(2); + }); + + it('names one selector from a selector list', async () => { + const css = `.a,\n.b::before:hover:dir(rtl) { left: unset; }`; + const { diagnostics } = await autoprefixCss(css, null); + + expect(diagnostics[0].messageText).toContain('.b::before:hover:dir(rtl)'); + }); + + it('keeps the original message for non-selector errors', async () => { + const { diagnostics } = await autoprefixCss(`.a { color: red; } }`, null); + + expect(diagnostics).toHaveLength(1); + expect(diagnostics[0].messageText).toBe('Unexpected end of input'); + }); +}); diff --git a/packages/core/src/compiler/optimize/autoprefixer.ts b/packages/core/src/compiler/optimize/autoprefixer.ts index ecf3322af36..32214066bc7 100644 --- a/packages/core/src/compiler/optimize/autoprefixer.ts +++ b/packages/core/src/compiler/optimize/autoprefixer.ts @@ -88,6 +88,15 @@ export const autoprefixCss = async ( diagnostic.messageText = e.message; } + if (e.data?.type === 'SelectorError' && e.loc && typeof e.loc.line === 'number') { + diagnostic.messageText = getSelectorErrorMessage( + typeof e.source === 'string' ? e.source : cssText, + e.loc, + diagnostic.messageText, + e.data.value?.type, + ); + } + // Extract file path from lightningcss error if (filePath) { diagnostic.absFilePath = filePath; @@ -131,6 +140,44 @@ export const autoprefixCss = async ( return output; }; +/** + * Lightning CSS selector errors (e.g. `Invalid state`) don't name the selector, and for + * preprocessed styles the reported line is in the compiled CSS, not the source file. + * @param sourceText the CSS that failed to parse + * @param loc the 1-based error location reported by Lightning CSS + * @param loc.line the error line + * @param loc.column the error column + * @param message the original error message + * @param errorType the Lightning CSS selector error type + * @returns a message that includes the offending selector + */ +const getSelectorErrorMessage = ( + sourceText: string, + loc: { line: number; column?: number }, + message: string, + errorType?: string, +) => { + const lines = sourceText.split('\n'); + const offset = + lines.slice(0, loc.line - 1).reduce((acc, line) => acc + line.length + 1, 0) + + (loc.column ?? 1) - + 1; + const start = Math.max( + sourceText.lastIndexOf('{', offset), + sourceText.lastIndexOf('}', offset), + sourceText.lastIndexOf(';', offset), + ); + const end = sourceText.indexOf('{', offset); + const selector = sourceText.slice(start + 1, end === -1 ? undefined : end).trim(); + if (!selector) return message; + + const hint = + errorType === 'InvalidState' + ? ` A pseudo-class can't follow a pseudo-element (e.g. \`::before:dir(rtl)\`); move it before (\`:dir(rtl)::before\`).` + : ''; + return `Invalid CSS selector "${selector}": ${message}.${hint}`; +}; + /** * Default browserslist targets used when autoprefixing CSS. * Targets ES2017 browsers (2022+) only. diff --git a/packages/core/src/compiler/output-targets/dist-lazy/_test_/cjs-import-meta-url-plugin.spec.ts b/packages/core/src/compiler/output-targets/dist-lazy/_test_/cjs-import-meta-url-plugin.spec.ts new file mode 100644 index 00000000000..5faa823cbef --- /dev/null +++ b/packages/core/src/compiler/output-targets/dist-lazy/_test_/cjs-import-meta-url-plugin.spec.ts @@ -0,0 +1,53 @@ +import { resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { rolldown } from 'rolldown'; +import { describe, expect, it } from 'vitest'; + +import { cjsImportMetaUrlPlugin } from '../cjs-import-meta-url-plugin'; + +const ENTRY_ID = 'entry.js'; + +const bundleCjs = async (source: string, plugins = [cjsImportMetaUrlPlugin(false)]) => { + const build = await rolldown({ + input: ENTRY_ID, + platform: 'browser', + logLevel: 'silent', + plugins: [ + { + name: 'virtual-entry', + resolveId: (id) => (id === ENTRY_ID ? id : null), + load: (id) => (id === ENTRY_ID ? source : null), + }, + ], + }); + const { output } = await build.generate({ format: 'cjs', plugins }); + return output[0].code; +}; + +describe('cjsImportMetaUrlPlugin', () => { + const source = `export const url = new URL('../assets/', String(import.meta.url)).href;`; + + it('renders `import.meta.url` as `{}.url` without the plugin', async () => { + expect(await bundleCjs(source, [])).toContain('String({}.url)'); + }); + + it('resolves `import.meta.url` from `__filename`', async () => { + const code = await bundleCjs(source); + expect(code).toContain('String(require("url").pathToFileURL(__filename).href)'); + expect(code).not.toContain('{}.url'); + }); + + it('produces a URL that evaluates under CommonJS', async () => { + const code = await bundleCjs(source); + const module = { exports: {} as { url?: string } }; + const filename = resolve('/pkg/dist/cjs/loader.cjs'); + new Function('module', 'exports', 'require', '__filename', code)( + module, + module.exports, + require, + filename, + ); + // resolved per platform (Windows adds a drive letter) + expect(module.exports.url).toBe(pathToFileURL(resolve('/pkg/dist/assets')).href + '/'); + }); +}); diff --git a/packages/core/src/compiler/output-targets/dist-lazy/_test_/generate-cjs.spec.ts b/packages/core/src/compiler/output-targets/dist-lazy/_test_/generate-cjs.spec.ts new file mode 100644 index 00000000000..3dea11122db --- /dev/null +++ b/packages/core/src/compiler/output-targets/dist-lazy/_test_/generate-cjs.spec.ts @@ -0,0 +1,46 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; +import type * as d from '@stencil/core'; +import type { RolldownBuild } from 'rolldown'; + +import { mockValidatedConfig } from '../../../../testing'; +import { mockBuildCtx, mockCompilerCtx } from '../../../../testing/compiler'; +import { DIST_LAZY, join } from '../../../../utils'; +import * as bundleAppCoreMod from '../../../app-core/bundle-app-core'; +import { generateCjs } from '../generate-cjs'; +import * as generateLazyModuleMod from '../generate-lazy-module'; + +describe('generateCjs', () => { + const indexResult = { + type: 'chunk', + fileName: 'index.cjs', + entryKey: 'index', + isIndex: true, + } as d.RolldownChunkResult; + + beforeEach(() => { + vi.spyOn(bundleAppCoreMod, 'generateRolldownOutput').mockResolvedValue([indexResult]); + vi.spyOn(generateLazyModuleMod, 'generateLazyModules').mockResolvedValue([]); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('scopes the cjs dir as commonjs so `.js` chunks load under a `"type": "module"` package', async () => { + const config = mockValidatedConfig(); + const compilerCtx = mockCompilerCtx(config); + vi.spyOn(compilerCtx.fs, 'writeFile'); + const buildCtx = mockBuildCtx(config, compilerCtx); + const cjsDir = join(config.rootDir, 'dist', 'loader-bundle', 'cjs'); + + await generateCjs(config, compilerCtx, buildCtx, {} as RolldownBuild, [ + { type: DIST_LAZY, cjsDir }, + ]); + + expect(compilerCtx.fs.writeFile).toHaveBeenCalledWith( + join(cjsDir, 'package.json'), + `{"type":"commonjs"}\n`, + { outputTargetType: DIST_LAZY }, + ); + }); +}); diff --git a/packages/core/src/compiler/output-targets/dist-lazy/cjs-import-meta-url-plugin.ts b/packages/core/src/compiler/output-targets/dist-lazy/cjs-import-meta-url-plugin.ts new file mode 100644 index 00000000000..0aa2e642c29 --- /dev/null +++ b/packages/core/src/compiler/output-targets/dist-lazy/cjs-import-meta-url-plugin.ts @@ -0,0 +1,28 @@ +import MagicString from 'magic-string'; +import type { Plugin } from 'rolldown'; + +/** + * With `platform: 'browser'` (shared with the ESM output), Rolldown renders `import.meta.url` + * in CJS as `{}.url`. Replace it with the same expression Rolldown emits for `platform: 'node'`. + */ +const EMPTY_IMPORT_META_URL = /\{\}\.url\b/g; +const CJS_FILE_URL = `require("url").pathToFileURL(__filename).href`; + +/** + * A Rolldown output plugin that restores `import.meta.url` in CJS chunks. + * @param sourceMap whether to generate a source map for the replacement + * @returns a Rolldown plugin + */ +export const cjsImportMetaUrlPlugin = (sourceMap: boolean): Plugin => ({ + name: 'cjsImportMetaUrlPlugin', + renderChunk(code) { + if (!code.includes('{}.url')) return null; + + const s = new MagicString(code); + s.replaceAll(EMPTY_IMPORT_META_URL, CJS_FILE_URL); + return { + code: s.toString(), + map: sourceMap ? s.generateMap({ hires: true }) : null, + }; + }, +}); diff --git a/packages/core/src/compiler/output-targets/dist-lazy/generate-cjs.ts b/packages/core/src/compiler/output-targets/dist-lazy/generate-cjs.ts index eeafcb4331c..7fd78f32cb2 100644 --- a/packages/core/src/compiler/output-targets/dist-lazy/generate-cjs.ts +++ b/packages/core/src/compiler/output-targets/dist-lazy/generate-cjs.ts @@ -8,6 +8,7 @@ import { relativeImport, } from '../../../utils'; import { generateRolldownOutput } from '../../app-core/bundle-app-core'; +import { cjsImportMetaUrlPlugin } from './cjs-import-meta-url-plugin'; import { generateLazyModules } from './generate-lazy-module'; import { lazyBundleIdPlugin } from './lazy-bundleid-plugin'; @@ -28,7 +29,10 @@ export const generateCjs = async ( entryFileNames: '[name].cjs', assetFileNames: '[name]-[hash][extname]', ...getRolldownSourceMapOptions(config), - plugins: [lazyBundleIdPlugin(buildCtx, config, false, 8, '.cjs')], + plugins: [ + lazyBundleIdPlugin(buildCtx, config, false, 8, '.cjs'), + cjsImportMetaUrlPlugin(!!config.sourceMap), + ], }; // Note: interop and dynamicImportInCjs options are not supported in Rolldown @@ -59,12 +63,29 @@ export const generateCjs = async ( ); await generateShortcuts(compilerCtx, results, cjsOutputs); + await writeCjsPackageJson(compilerCtx, cjsOutputs); } } return { name: 'cjs', buildCtx }; }; +/** + * Chunks and lazy entries in the CJS dir keep a `.js` extension, so scope them as CommonJS + * in case the consuming package sets `"type": "module"`. + * @param compilerCtx the current compiler context + * @param outputTargets the output targets with a CJS dir + * @returns a promise that resolves once each `package.json` is written + */ +const writeCjsPackageJson = (compilerCtx: d.CompilerCtx, outputTargets: d.OutputTargetDistLazy[]) => + Promise.all( + outputTargets.map((o) => + compilerCtx.fs.writeFile(join(o.cjsDir, 'package.json'), `{"type":"commonjs"}\n`, { + outputTargetType: o.type, + }), + ), + ); + const generateShortcuts = ( compilerCtx: d.CompilerCtx, rolldownResult: d.RolldownResult[], diff --git a/test/build/outputs/test-output-targets.js b/test/build/outputs/test-output-targets.js index 8fa6cc45d78..d63323ca208 100644 --- a/test/build/outputs/test-output-targets.js +++ b/test/build/outputs/test-output-targets.js @@ -1,4 +1,6 @@ +import assert from 'node:assert/strict'; import fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -24,6 +26,21 @@ fs.accessSync(path.join(loaderBundleDir, 'loader', 'index.js')); fs.accessSync(path.join(loaderBundleDir, 'loader', 'index.cjs')); fs.accessSync(path.join(loaderBundleDir, 'loader', 'index.d.ts')); +// cjs chunks / lazy entries keep `.js`; they must still load as CJS under this `"type": "module"` package +const cjsDir = path.join(loaderBundleDir, 'cjs'); +const requireCjs = createRequire(path.join(cjsDir, 'noop.cjs')); +const cjsJsFiles = fs.readdirSync(cjsDir).filter((f) => f.endsWith('.js')); +const runtimeChunk = cjsJsFiles.find((f) => f.startsWith('runtime-')); +const lazyEntry = cjsJsFiles.find((f) => f.endsWith('.entry.js')); +assert.ok(runtimeChunk, 'expected a cjs runtime chunk'); +assert.ok(lazyEntry, 'expected a cjs lazy entry'); +assert.equal(typeof requireCjs(`./${runtimeChunk}`).bootstrapLazy, 'function'); +assert.ok(Object.keys(requireCjs(`./${lazyEntry}`)).length > 0, `${lazyEntry} has no exports`); +// loader sets an asset path from `import.meta.url` at module scope +const cjsLoader = requireCjs('../loader/index.cjs'); +assert.equal(typeof cjsLoader.defineCustomElements, 'function'); +assert.equal(typeof cjsLoader.setAssetPath, 'function'); + // collection output (was collection) const collectionDir = path.join(distDir, 'collection'); fs.accessSync(path.join(collectionDir, 'car-list', 'car-data.js'));