diff --git a/.changelog/6091-feat-tsdown-remove-tsup.md b/.changelog/6091-feat-tsdown-remove-tsup.md new file mode 100644 index 0000000000..1934654b9c --- /dev/null +++ b/.changelog/6091-feat-tsdown-remove-tsup.md @@ -0,0 +1,3 @@ +### Changed + +- Built the `static/` folders with rolldown instead of esbuild, and removed tsup, in PR [#6091](https://github.com/microsoft/BotFramework-WebChat/pull/6091), by [@OEvgeny](https://github.com/OEvgeny) diff --git a/__tests__/html2/boot/bundle.html b/__tests__/html2/boot/bundle.html index cc60a78db3..ea5bbffbbe 100644 --- a/__tests__/html2/boot/bundle.html +++ b/__tests__/html2/boot/bundle.html @@ -42,7 +42,7 @@ // THEN: It should have ``. expect(metaMap.has('botframework-webchat:api')).toBe(true); expect(metaMap.get('botframework-webchat:api')).toEqual( - expect.stringMatching(/build-tool=(tsup|tsdown)(;|$)/u) + expect.stringMatching(/build-tool=tsdown(;|$)/u) ); expect(metaMap.get('botframework-webchat:api')).toEqual(expect.stringContaining('module-format=')); expect(metaMap.get('botframework-webchat:api')).toEqual(expect.stringContaining('version=')); @@ -50,7 +50,7 @@ // THEN: It should have ``. expect(metaMap.has('botframework-webchat')).toBe(true); - expect(metaMap.get('botframework-webchat')).toEqual(expect.stringMatching(/build-tool=(tsup|tsdown)(;|$)/u)); + expect(metaMap.get('botframework-webchat')).toEqual(expect.stringMatching(/build-tool=tsdown(;|$)/u)); expect(metaMap.get('botframework-webchat')).toEqual(expect.stringContaining('module-format=global')); expect(metaMap.get('botframework-webchat')).toEqual(expect.stringContaining(`variant=${variant}`)); expect(metaMap.get('botframework-webchat')).toEqual(expect.stringContaining('version=')); @@ -59,7 +59,7 @@ // THEN: It should have ``. expect(metaMap.has('botframework-webchat:component')).toBe(true); expect(metaMap.get('botframework-webchat:component')).toEqual( - expect.stringMatching(/build-tool=(tsup|tsdown)(;|$)/u) + expect.stringMatching(/build-tool=tsdown(;|$)/u) ); expect(metaMap.get('botframework-webchat:component')).toEqual(expect.stringContaining('module-format=')); expect(metaMap.get('botframework-webchat:component')).toEqual(expect.stringContaining('version=')); @@ -68,7 +68,7 @@ // THEN: It should have ``. expect(metaMap.has('botframework-webchat:core')).toBe(true); expect(metaMap.get('botframework-webchat:core')).toEqual( - expect.stringMatching(/build-tool=(tsup|tsdown)(;|$)/u) + expect.stringMatching(/build-tool=tsdown(;|$)/u) ); expect(metaMap.get('botframework-webchat:core')).toEqual(expect.stringContaining('module-format=')); expect(metaMap.get('botframework-webchat:core')).toEqual(expect.stringContaining('version=')); @@ -112,8 +112,8 @@ expect(WebChat.Components.AdaptiveCardContent).toBeUndefined(); } - // THEN: `buildInfo.buildTool` should be "tsup" or "tsdown". - expect(WebChat).toHaveProperty('buildInfo.buildTool', expect.stringMatching(/^(tsup|tsdown)$/u)); + // THEN: `buildInfo.buildTool` should be "tsdown". + expect(WebChat).toHaveProperty('buildInfo.buildTool', 'tsdown'); // THEN: `buildInfo.moduleFromat` should be "global". expect(WebChat).toHaveProperty('buildInfo.moduleFormat', 'global'); // Bundle diff --git a/__tests__/html2/fluentTheme/simple.html b/__tests__/html2/fluentTheme/simple.html index 7a6de6f3d5..dbda508b5c 100644 --- a/__tests__/html2/fluentTheme/simple.html +++ b/__tests__/html2/fluentTheme/simple.html @@ -47,7 +47,7 @@ .map(value => value.trim().split('=')) ); - expect(buildInfo).toHaveProperty('build-tool', expect.stringMatching(/^(tsup|tsdown)$/u)); + expect(buildInfo).toHaveProperty('build-tool', 'tsdown'); expect(buildInfo).toHaveProperty('module-format', 'global'); expect(buildInfo.version).toMatch(/^\d+\.\d+\.\d+($|-)/u); diff --git a/__tests__/html2/preact/fluentTheme/simple.html b/__tests__/html2/preact/fluentTheme/simple.html index d6f79dc76b..adeb07b95e 100644 --- a/__tests__/html2/preact/fluentTheme/simple.html +++ b/__tests__/html2/preact/fluentTheme/simple.html @@ -53,7 +53,7 @@ .map(value => value.trim().split('=')) ); - expect(buildInfo).toHaveProperty('build-tool', expect.stringMatching(/^(tsup|tsdown)$/u)); + expect(buildInfo).toHaveProperty('build-tool', 'tsdown'); expect(buildInfo).toHaveProperty('module-format', 'global'); expect(buildInfo.version).toMatch(/^\d+\.\d+\.\d+($|-)/u); diff --git a/esbuildBabelPluginIstanbul.babel.config.json b/babelPluginIstanbul.config.json similarity index 100% rename from esbuildBabelPluginIstanbul.babel.config.json rename to babelPluginIstanbul.config.json diff --git a/esbuildBabelPluginIstanbul.ts b/esbuildBabelPluginIstanbul.ts deleted file mode 100644 index cc01d0db16..0000000000 --- a/esbuildBabelPluginIstanbul.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { transformFileAsync } from '@babel/core'; -import { OnLoadArgs, OnLoadOptions, OnLoadResult, Plugin } from 'esbuild'; -import { join } from 'path'; -import { fileURLToPath } from 'url'; - -export type Predicate = (args: OnLoadArgs) => boolean; - -export type IstanbulPluginConfig = { - filter: OnLoadOptions['filter']; - loader: OnLoadResult['loader']; - name: Plugin['name']; - predicate?: Predicate | undefined; -}; - -export const defaultPredicate: Predicate = args => !args.path.includes('/node_modules/'); - -export const babelPlugin = ({ filter, loader, name, predicate = defaultPredicate }: IstanbulPluginConfig): Plugin => ({ - name, - setup(build) { - build.onLoad({ filter }, async args => { - if (!predicate(args)) { - return; - } - - const result = await transformFileAsync(args.path, { - configFile: join(fileURLToPath(import.meta.url), '../esbuildBabelPluginIstanbul.babel.config.json'), - rootMode: 'root', - sourceFileName: args.path - }); - - if (!result?.code) { - throw new Error(`Failed to add instrumentation code to ${args.path}.`); - } - - return { contents: result.code, loader }; - }); - } -}); diff --git a/esbuildPlugins.mjs b/esbuildPlugins.mjs deleted file mode 100644 index 57e887c804..0000000000 --- a/esbuildPlugins.mjs +++ /dev/null @@ -1,35 +0,0 @@ -import lightningCssPlugin from 'unplugin-lightningcss/esbuild'; - -import { lightningCSSPluginOptions, removePreserveReason, sortClassMap } from './lightningCSSOptions.mjs'; - -// Due to a bug in unplugin, we cannot use the Lightning CSS unplugin directly. -// https://github.com/unjs/unplugin/issues/546 -// To workaround the bug, we are converting it back to esbuild plugin so we can apply a custom `filter`. -// Otherwise, unplugin will apply `filter: /.*/` and trigger the bug down the road. - -/** @type { import('esbuild').Plugin } */ -const cssPlugin = { - name: 'lightningcss', - setup: build => { - lightningCssPlugin(lightningCSSPluginOptions).setup({ - ...build, - onLoad: (_filter, fn) => - // eslint-disable-next-line require-unicode-regexp - build.onLoad({ filter: /(\.module_built\.css|\?css_module)$/ }, async args => { - const result = await fn(args); - - // The CSS of a CSS module, or its JavaScript class map. - return typeof result?.contents === 'string' - ? { - ...result, - contents: args.path.endsWith('.module_built.css') - ? removePreserveReason(result.contents, args.path) - : sortClassMap(result.contents, args.path) - } - : result; - }) - }); - } -}; - -export { cssPlugin }; diff --git a/lightningCSSOptions.mjs b/lightningCSSOptions.mjs index c0b216f31e..db66ab7788 100644 --- a/lightningCSSOptions.mjs +++ b/lightningCSSOptions.mjs @@ -19,7 +19,7 @@ const removePreserveReasonVisitor = Object.freeze({ /** * Options of unplugin-lightningcss. * - * @type { NonNullable[0]> } + * @type { NonNullable[0]> } */ const lightningCSSPluginOptions = Object.freeze({ include: [/\.module\.css$/u], diff --git a/package-lock.json b/package-lock.json index ae1b685c76..2011231c46 100644 --- a/package-lock.json +++ b/package-lock.json @@ -110,7 +110,6 @@ "selenium-webdriver": "^4.44.0", "strip-ansi": "^6.0.1", "tsdown": "^0.23.7", - "tsup": "^9.0.0", "typescript": "^6.0.3", "unplugin-lightningcss": "^0.4.5" } @@ -6789,11 +6788,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/any-promise": { - "version": "1.3.0", - "dev": true, - "license": "MIT" - }, "node_modules/anymatch": { "version": "3.1.3", "dev": true, @@ -8462,19 +8456,6 @@ "node": "^20.19.0 || ^22.12.0 || >=23" } }, - "node_modules/confbox": { - "version": "0.1.8", - "dev": true, - "license": "MIT" - }, - "node_modules/consola": { - "version": "3.4.2", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.18.0 || >=16.10.0" - } - }, "node_modules/content-disposition": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", @@ -10684,16 +10665,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/fix-dts-default-cjs-exports": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "magic-string": "^0.30.17", - "mlly": "^1.7.4", - "rollup": "^4.34.8" - } - }, "node_modules/flat": { "version": "5.0.2", "dev": true, @@ -14280,14 +14251,6 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/joycon": { - "version": "3.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, "node_modules/js-tokens": { "version": "4.0.0", "license": "MIT" @@ -14789,17 +14752,6 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/lilconfig": { - "version": "3.1.3", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/antonk52" - } - }, "node_modules/lines-and-columns": { "version": "1.2.4", "license": "MIT" @@ -14865,14 +14817,6 @@ "dev": true, "license": "MIT" }, - "node_modules/load-tsconfig": { - "version": "0.2.5", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - } - }, "node_modules/loader-runner": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.2.tgz", @@ -15138,15 +15082,6 @@ "lz-string": "bin/bin.js" } }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, "node_modules/make-dir": { "version": "2.1.0", "dev": true, @@ -16139,31 +16074,10 @@ "node": ">=10" } }, - "node_modules/mlly": { - "version": "1.7.4", - "dev": true, - "license": "MIT", - "dependencies": { - "acorn": "^8.14.0", - "pathe": "^2.0.1", - "pkg-types": "^1.3.0", - "ufo": "^1.5.4" - } - }, "node_modules/ms": { "version": "2.1.3", "license": "MIT" }, - "node_modules/mz": { - "version": "2.7.0", - "dev": true, - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0", - "object-assign": "^4.0.1", - "thenify-all": "^1.0.0" - } - }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -16893,11 +16807,6 @@ "node": ">=8" } }, - "node_modules/pathe": { - "version": "2.0.3", - "dev": true, - "license": "MIT" - }, "node_modules/pend": { "version": "1.2.0", "dev": true, @@ -16954,16 +16863,6 @@ "node": ">=12.13.0" } }, - "node_modules/pkg-types": { - "version": "1.3.1", - "dev": true, - "license": "MIT", - "dependencies": { - "confbox": "^0.1.8", - "mlly": "^1.7.4", - "pathe": "^2.0.1" - } - }, "node_modules/pkijs": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.3.3.tgz", @@ -17038,47 +16937,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/postcss-load-config": { - "version": "6.0.1", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "lilconfig": "^3.1.1" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "jiti": ">=1.21.0", - "postcss": ">=8.0.9", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - }, - "postcss": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, "node_modules/postcss-modules-extract-imports": { "version": "3.1.0", "dev": true, @@ -19560,36 +19418,6 @@ "node": ">= 12" } }, - "node_modules/sucrase": { - "version": "3.35.1", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", - "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", - "dev": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.2", - "commander": "^4.0.0", - "lines-and-columns": "^1.1.6", - "mz": "^2.7.0", - "pirates": "^4.0.1", - "tinyglobby": "^0.2.11", - "ts-interface-checker": "^0.1.9" - }, - "bin": { - "sucrase": "bin/sucrase", - "sucrase-node": "bin/sucrase-node" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/sucrase/node_modules/commander": { - "version": "4.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, "node_modules/supports-color": { "version": "5.5.0", "dev": true, @@ -19910,25 +19738,6 @@ "dev": true, "license": "MIT" }, - "node_modules/thenify": { - "version": "3.3.1", - "dev": true, - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0" - } - }, - "node_modules/thenify-all": { - "version": "1.6.0", - "dev": true, - "license": "MIT", - "dependencies": { - "thenify": ">= 3.1.0 < 4" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/tinyexec": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", @@ -20069,11 +19878,6 @@ "typescript": ">=4.8.4" } }, - "node_modules/ts-interface-checker": { - "version": "0.1.13", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/tsconfig-paths": { "version": "3.15.0", "dev": true, @@ -20215,103 +20019,6 @@ "version": "2.8.1", "license": "0BSD" }, - "node_modules/tsup": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/tsup/-/tsup-9.0.0.tgz", - "integrity": "sha512-DHgb0bfo2gFKybOa8dRFMiHSqzWWhMkfNK0f902VVquWQtDBWExNgidHszjjDKaFd12pWPgzumpWf9nGr3gzFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "bundle-require": "^5.1.0", - "cac": "^7.1.0", - "chokidar": "^5.0.0", - "consola": "^3.4.2", - "esbuild": "^0.28.2", - "fix-dts-default-cjs-exports": "^1.0.1", - "joycon": "^3.1.1", - "obug": "^3.0.0", - "picocolors": "^1.1.1", - "postcss-load-config": "^6.0.1", - "resolve-from": "^5.0.0", - "rollup": "^4.64.6", - "source-map-js": "^1.2.2", - "sucrase": "^3.35.1", - "tinyexec": "^1.3.1", - "tinyglobby": "^0.2.17", - "tree-kill": "^1.2.2" - }, - "bin": { - "tsup": "dist/cli-default.js", - "tsup-node": "dist/cli-node.js" - }, - "engines": { - "node": "^22.18.0 || ^24.11.0 || >=26.0.0" - }, - "peerDependencies": { - "@microsoft/api-extractor": "^7.36.0", - "@swc/core": "^1", - "postcss": "^8.4.12", - "typescript": ">=4.5.0" - }, - "peerDependenciesMeta": { - "@microsoft/api-extractor": { - "optional": true - }, - "@swc/core": { - "optional": true - }, - "postcss": { - "optional": true - }, - "typescript": { - "optional": true - } - } - }, - "node_modules/tsup/node_modules/bundle-require": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "load-tsconfig": "^0.2.3" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "peerDependencies": { - "esbuild": ">=0.18" - } - }, - "node_modules/tsup/node_modules/chokidar": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", - "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", - "dev": true, - "license": "MIT", - "dependencies": { - "readdirp": "^5.0.0" - }, - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/tsup/node_modules/readdirp": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", - "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - }, "node_modules/tsyringe": { "version": "4.10.0", "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz", @@ -20603,11 +20310,6 @@ "node": ">= 6" } }, - "node_modules/ufo": { - "version": "1.6.1", - "dev": true, - "license": "MIT" - }, "node_modules/unbox-primitive": { "version": "1.1.0", "dev": true, @@ -21913,9 +21615,9 @@ "babel-plugin-istanbul": "^8.0.0", "babel-plugin-transform-inline-environment-variables": "^0.4.4", "cross-env": "^10.1.0", - "esbuild": "^0.28.1", "micromark-util-types": "^2.0.2", "read-pkg": "^10.1.0", + "rolldown": "~1.3.0", "tsd": "^0.33.0", "type-fest": "^5.6.0", "typescript": "^6.0.3" @@ -22403,6 +22105,7 @@ "@types/node": "^25.9.1", "@types/react": "^16.14.70", "concurrently": "^10.0.6", + "rolldown": "~1.3.0", "tsdown": "^0.23.7", "typescript": "^6.0.3" }, @@ -22896,11 +22599,11 @@ "license": "MIT", "devDependencies": { "@jridgewell/sourcemap-codec": "^1.5.5", + "@jridgewell/trace-mapping": "^0.3.29", "@msinternal/botframework-webchat-base": "0.0.0-0", "@msinternal/botframework-webchat-tsconfig": "0.0.0-0", "@types/node": "^25.9.1", "cross-env": "^10.1.0", - "esbuild": "^0.28.1", "tsdown": "^0.23.7", "type-fest": "^5.6.0", "typescript": "^6.0.3" diff --git a/package.json b/package.json index 1c0392a7e1..e9f5d241f9 100644 --- a/package.json +++ b/package.json @@ -291,7 +291,6 @@ "selenium-webdriver": "^4.44.0", "strip-ansi": "^6.0.1", "tsdown": "^0.23.7", - "tsup": "^9.0.0", "typescript": "^6.0.3", "unplugin-lightningcss": "^0.4.5" }, diff --git a/packages/bundle/esbuild.static.mjs b/packages/bundle/esbuild.static.mjs deleted file mode 100644 index 926bf32d9b..0000000000 --- a/packages/bundle/esbuild.static.mjs +++ /dev/null @@ -1,268 +0,0 @@ -/// - -/* eslint-env node */ -/* eslint-disable no-console */ -/* eslint-disable no-magic-numbers */ -/* eslint-disable no-restricted-globals */ - -import { injectCSSPlugin } from '@msinternal/botframework-webchat-styles/build'; -import { mkdir, writeFile } from 'fs/promises'; -import { build, context } from 'esbuild'; -import { dirname, resolve } from 'path'; -import { readPackage } from 'read-pkg'; -import { fileURLToPath } from 'url'; -import { cssPlugin } from '../../esbuildPlugins.mjs'; - -// TODO: [P0] We cannot import TypeScript file here. -const bundleStyleContentPlaceholder = '@--BUNDLE-STYLES-CONTENT--@'; - -// eslint-disable-next-line no-unused-vars -const isomorphicReactPlugin = { - name: 'isomorphic-react', - setup(build) { - // eslint-disable-next-line require-unicode-regexp - build.onResolve({ filter: /^(react|react-dom)$/, namespace: 'file' }, ({ path }) => ({ - namespace: 'isomorphic-react', - path - })); - - // eslint-disable-next-line require-unicode-regexp - build.onLoad({ filter: /^react$/, namespace: 'isomorphic-react' }, () => ({ - contents: "import React from 'react'; module.exports = globalThis.React || React;" - })); - - // eslint-disable-next-line require-unicode-regexp - build.onLoad({ filter: /^react-dom$/, namespace: 'isomorphic-react' }, () => ({ - contents: "import ReactDOM from 'react-dom'; module.exports = globalThis.ReactDOM || ReactDOM;" - })); - } -}; - -function createWatcherPlugin(name) { - /** @type { import('esbuild').Plugin } */ - return { - name: 'watcher', - setup(build) { - let buildStart = Date.now(); - - console.log(`${name} Running in watch mode`); - - build.onStart(() => { - buildStart = Date.now(); - console.log(`${name} Build start`); - }); - - build.onEnd(() => console.log(`${name} ⚡ Build success in ${Date.now() - buildStart}ms`)); - } - }; -} - -/** @type { Map } */ -const configs = new Map(); - -const BASE_CONFIG = { - alias: { - adaptivecards: '@msinternal/adaptivecards', - 'base64-js': '@msinternal/base64-js', - 'botframework-directlinejs': '@msinternal/botframework-directlinejs', - 'html-react-parser': '@msinternal/html-react-parser', - 'microsoft-cognitiveservices-speech-sdk': '@msinternal/microsoft-cognitiveservices-speech-sdk', - 'object-assign': '@msinternal/object-assign', - 'react-is': '@msinternal/react-is' - }, - bundle: true, - chunkNames: 'botframework-webchat/[name]-[hash]', - entryNames: '[dir]/[name]', - external: ['react', 'react-dom'], - format: 'esm', - loader: { '.js': 'jsx' }, - minify: true, - outdir: resolve(fileURLToPath(import.meta.url), `../static/`), - platform: 'browser', - metafile: true, - plugins: [ - cssPlugin, - injectCSSPlugin({ - ignoreCSSEntries: ['static/botframework-webchat/component.css'], - stylesPlaceholder: bundleStyleContentPlaceholder - }), - { - // `write` is set to `false`, we need to emit files ourselves. - name: 'emit-output', - setup(build) { - build.onEnd(async args => { - await Promise.all( - args.outputFiles.map(async entry => { - // eslint-disable-next-line security/detect-non-literal-fs-filename - await mkdir(dirname(entry.path), { recursive: true }); - - // eslint-disable-next-line security/detect-non-literal-fs-filename - await writeFile(entry.path, entry.contents); - }) - ); - }); - } - } - ], - sourcemap: true, - splitting: true, - target: ['chrome100', 'firefox100', 'safari15'], - // Set write to false for the `injectCSSPlugin` to work. - // We will emit the output in another plugin. - write: false -}; - -function* getKeysRecursive(exports) { - for (const [key, value] of Object.entries(exports)) { - yield key; - - if (typeof value !== 'string') { - yield* getKeysRecursive(value); - } - } -} - -const IGNORED_OWN_PACKAGES = [ - // Not exporting Direct Line Speech. - 'botframework-directlinespeech-sdk', - // We will export bundle from `/src/boot/` folder directly. - 'botframework-webchat', - // `fluent-theme` is higher level than bundle, we will export from the package itself separately. - 'botframework-webchat-fluent-theme' -]; - -(async () => { - // eslint-disable-next-line prefer-destructuring - const [_0, _1, watch] = process.argv; - - const { workspaces } = await readPackage({ cwd: resolve(fileURLToPath(import.meta.url), '../../../') }); - - const allOwnExports = new Map(); - - for (const path of workspaces) { - // eslint-disable-next-line no-await-in-loop - const packageJson = await readPackage({ cwd: resolve(fileURLToPath(import.meta.url), '../../..', path) }); - - if (packageJson.private || !packageJson.exports || IGNORED_OWN_PACKAGES.includes(packageJson.name)) { - continue; - } - - const { name: packageName } = packageJson; - - for (const key of getKeysRecursive(packageJson.exports)) { - if (key.startsWith('.')) { - if (key === '.') { - allOwnExports.set(packageName, packageName); - } else if (key.endsWith('.js')) { - // We need to remove .js suffix otherwise, esbuild will emit filename.js.js. - // ./filename.js -> /filename - allOwnExports.set(`${packageName}${key.slice(1, -3)}`, `${packageName}${key.slice(1)}`); - } - } - } - } - - // Rules to select what packages to externalize: - // - All of our own published packages - // - Web devs can import our stuff just like they are on npm - // - Peer dependencies, such as `react` and `react-dom` - // - Web devs can use import map to reconfigure what version of dependencies they want - - const entryPoints = { - 'botframework-webchat': './src/boot/exports/index.ts', - 'botframework-webchat/component': './src/boot/exports/component.ts', - 'botframework-webchat/decorator': './src/boot/exports/decorator.ts', - 'botframework-webchat/hook': './src/boot/exports/hook.ts', - 'botframework-webchat/internal': './src/boot/exports/internal.ts', - 'botframework-webchat/middleware': './src/boot/exports/middleware.ts', - 'botframework-webchat/schema': './src/boot/exports/schema.ts', - // TODO: [P2] We can remove the `Array.from()` after bumping Node.js. - ...Object.fromEntries(allOwnExports) - }; - - console.log('Exporting the following own entry points:'); - console.log(entryPoints); - - configs.set('botframework-webchat', { - chunkNames: `[name]-[hash]`, - entryNames: `[dir]/[name]`, - entryPoints - }); - - // Put `react` and `react-dom` under `/static` for conveniences when using in sovereign cloud or airgapped environment. - configs.set('react', { - chunkNames: `react/[name]-[hash]`, - entryNames: `[dir]/[name]`, - entryPoints: { - react: '@msinternal/react', - 'react/jsx-dev-runtime': '@msinternal/react/jsx-dev-runtime', - 'react/jsx-runtime': '@msinternal/react/jsx-runtime' - } - }); - - configs.set('react-dom', { - chunkNames: `react-dom/[name]-[hash]`, - entryNames: `[dir]/[name]`, - entryPoints: { - 'react-dom': '@msinternal/react-dom', - 'react-dom/client': '@msinternal/react-dom/client' - } - }); - - configs.set('react-baseline', { - chunkNames: `react.baseline/[name]-[hash]`, // Some web servers are not good at handling @. - entryNames: `[dir]/[name]`, - entryPoints: { - 'react.baseline': '@msinternal/react-baseline' - } - }); - - configs.set('react-dom-baseline', { - chunkNames: `react-dom.baseline/[name]-[hash]`, // Some web servers are not good at handling @. - entryNames: `[dir]/[name]`, - entryPoints: { - 'react-dom.baseline': '@msinternal/react-dom-baseline' - } - }); - - configs.set('react-umd', { - chunkNames: `react.umd/[name]-[hash]`, // Some web servers are not good at handling @. - entryNames: `[dir]/[name]`, - entryPoints: { - 'react.umd-development': '@msinternal/react-umd' - } - }); - - configs.set('react-dom-umd', { - chunkNames: `react-dom.umd/[name]-[hash]`, // Some web servers are not good at handling @. - entryNames: `[dir]/[name]`, - entryPoints: { - 'react-dom.umd-development': '@msinternal/react-dom-umd' - } - }); - - await Promise.all( - Array.from(configs.values()).map(config => - build({ - ...config, - ...BASE_CONFIG - }) - ) - ); - - if (watch === '--watch') { - const ourConfigs = []; - - for (const [key, config] of configs) { - if (key.startsWith('botframework-webchat')) { - const ourConfig = { ...config, ...BASE_CONFIG }; - - ourConfig.plugins = [...(ourConfig.plugins || []), createWatcherPlugin(key)]; - - ourConfigs.push(ourConfig); - } - } - - await Promise.all(ourConfigs.map(async config => (await context(config)).watch({ delay: 200 }))); - } -})(); diff --git a/packages/bundle/package.json b/packages/bundle/package.json index eb02aac39c..addbfc2525 100644 --- a/packages/bundle/package.json +++ b/packages/bundle/package.json @@ -159,12 +159,12 @@ "build:post:validate": "npm run build:post:validate:css && npm run build:post:validate:inject-css && npm run build:post:validate:dts", "build:post:validate:css": "vg ast-check lightning-css ./dist/*.css", "build:post:validate:dts": "vg ast-check dist-types ./dist/*.d.*", - "build:post:validate:inject-css": "vg ast-check css-inject dist/*.js dist/*.mjs static/*.js", + "build:post:validate:inject-css": "vg ast-check css-inject dist/*.js dist/*.mjs static/*.js static/*/*.js", "build:pre": "npm run build:pre:local-dependencies && npm run build:pre:watch", "build:pre:local-dependencies": "../../scripts/npm/build-local-dependencies.sh", "build:pre:watch": "../../scripts/npm/build-watch.sh", "build:run": "concurrently --prefix-colors \"auto\" \"npm:build:run:*\"", - "build:run:static": "node ./esbuild.static.mjs", + "build:run:static": "node ./rolldown.static.mjs", "build:run:tsdown": "tsdown", "bump": "vg bump prod && vg bump dev && (npm audit fix || exit 0)", "eslint": "npm run precommit", @@ -261,9 +261,9 @@ "babel-plugin-istanbul": "^8.0.0", "babel-plugin-transform-inline-environment-variables": "^0.4.4", "cross-env": "^10.1.0", - "esbuild": "^0.28.1", "micromark-util-types": "^2.0.2", "read-pkg": "^10.1.0", + "rolldown": "~1.3.0", "tsd": "^0.33.0", "type-fest": "^5.6.0", "typescript": "^6.0.3" diff --git a/packages/bundle/rolldown.static.mjs b/packages/bundle/rolldown.static.mjs new file mode 100644 index 0000000000..cbfcd0862d --- /dev/null +++ b/packages/bundle/rolldown.static.mjs @@ -0,0 +1,147 @@ +/// + +/* eslint-env node */ +/* eslint-disable no-console */ +/* eslint-disable no-magic-numbers */ +/* eslint-disable no-restricted-globals */ + +import { injectCSSRolldownPlugin } from '@msinternal/botframework-webchat-styles/build'; +import { resolve } from 'path'; +import { readPackage } from 'read-pkg'; +import { build } from 'rolldown'; +import { fileURLToPath } from 'url'; +import { cssPlugin, inputSourceMapPlugin } from '../../rolldownPlugins.mjs'; + +// TODO: [P0] We cannot import TypeScript file here. +const bundleStyleContentPlaceholder = '@--BUNDLE-STYLES-CONTENT--@'; + +const target = ['chrome100', 'firefox100', 'safari15']; + +const BASE_CONFIG = { + checks: { pluginTimings: false }, + external: /^react(?:-dom)?(?:\/|$)/u, + moduleTypes: { '.js': 'jsx' }, + output: { + chunkFileNames: 'botframework-webchat/chunk-[hash].js', + // Minified: legal comments only, rolldown keeps annotations and JSDoc by default. + comments: { annotation: false, jsdoc: false, legal: true }, + dir: resolve(fileURLToPath(import.meta.url), '../static/'), + entryFileNames: '[name].js', + format: 'esm', + minify: true, + sourcemap: true + }, + platform: 'browser', + resolve: { + alias: { + adaptivecards: '@msinternal/adaptivecards', + 'base64-js': '@msinternal/base64-js', + 'botframework-directlinejs': '@msinternal/botframework-directlinejs', + 'html-react-parser': '@msinternal/html-react-parser', + 'microsoft-cognitiveservices-speech-sdk': '@msinternal/microsoft-cognitiveservices-speech-sdk', + 'object-assign': '@msinternal/object-assign', + 'react-is': '@msinternal/react-is' + } + }, + // Browsers have no `process`: React and other packages read `process.env.NODE_ENV` to pick their production code. + transform: { define: { 'process.env.NODE_ENV': '"production"' }, target }, + tsconfig: './src/tsconfig.json' +}; + +function* getKeysRecursive(exports) { + for (const [key, value] of Object.entries(exports)) { + yield key; + + if (typeof value !== 'string') { + yield* getKeysRecursive(value); + } + } +} + +const IGNORED_OWN_PACKAGES = [ + // Not exporting Direct Line Speech. + 'botframework-directlinespeech-sdk', + // We will export bundle from `/src/boot/` folder directly. + 'botframework-webchat', + // `fluent-theme` is higher level than bundle, we will export from the package itself separately. + 'botframework-webchat-fluent-theme' +]; + +(async () => { + const { workspaces } = await readPackage({ cwd: resolve(fileURLToPath(import.meta.url), '../../../') }); + + const allOwnExports = new Map(); + + for (const path of workspaces) { + // eslint-disable-next-line no-await-in-loop + const packageJson = await readPackage({ cwd: resolve(fileURLToPath(import.meta.url), '../../..', path) }); + + if (packageJson.private || !packageJson.exports || IGNORED_OWN_PACKAGES.includes(packageJson.name)) { + continue; + } + + const { name: packageName } = packageJson; + + for (const key of getKeysRecursive(packageJson.exports)) { + if (key.startsWith('.')) { + if (key === '.') { + allOwnExports.set(packageName, packageName); + } else if (key.endsWith('.js')) { + // ./filename.js -> /filename, `entryFileNames` adds .js. + allOwnExports.set(`${packageName}${key.slice(1, -3)}`, `${packageName}${key.slice(1)}`); + } + } + } + } + + // Rules to select what packages to externalize: + // - All of our own published packages + // - Web devs can import our stuff just like they are on npm + // - Peer dependencies, such as `react` and `react-dom` + // - Web devs can use import map to reconfigure what version of dependencies they want + + const input = { + 'botframework-webchat': './src/boot/exports/index.ts', + 'botframework-webchat/component': './src/boot/exports/component.ts', + 'botframework-webchat/decorator': './src/boot/exports/decorator.ts', + 'botframework-webchat/hook': './src/boot/exports/hook.ts', + 'botframework-webchat/internal': './src/boot/exports/internal.ts', + 'botframework-webchat/middleware': './src/boot/exports/middleware.ts', + 'botframework-webchat/schema': './src/boot/exports/schema.ts', + ...Object.fromEntries(allOwnExports) + }; + + console.log('Exporting the following own entry points:'); + console.log(input); + + const configs = [ + { + input, + plugins: [ + cssPlugin({ minify: true, target }), + inputSourceMapPlugin(), + injectCSSRolldownPlugin({ + ignoreCSSEntries: ['static/botframework-webchat/component.css'], + stylesPlaceholder: bundleStyleContentPlaceholder + }) + ] + }, + // Put `react` and `react-dom` under `/static` for conveniences when using in sovereign cloud or airgapped environment. + { + input: { + react: '@msinternal/react', + 'react/jsx-dev-runtime': '@msinternal/react/jsx-dev-runtime', + 'react/jsx-runtime': '@msinternal/react/jsx-runtime' + } + }, + { input: { 'react-dom': '@msinternal/react-dom', 'react-dom/client': '@msinternal/react-dom/client' } }, + { input: { 'react.baseline': '@msinternal/react-baseline' } }, + { input: { 'react-dom.baseline': '@msinternal/react-dom-baseline' } }, + { input: { 'react.umd-development': '@msinternal/react-umd' } }, + { input: { 'react-dom.umd-development': '@msinternal/react-dom-umd' } } + ]; + + await Promise.all( + configs.map(({ input, plugins = [inputSourceMapPlugin()] }) => build({ ...BASE_CONFIG, input, plugins })) + ); +})(); diff --git a/packages/bundle/src/boot/exports/minimal.ts b/packages/bundle/src/boot/exports/minimal.ts index 3b02e91c6f..c0f67e7f6c 100644 --- a/packages/bundle/src/boot/exports/minimal.ts +++ b/packages/bundle/src/boot/exports/minimal.ts @@ -3,8 +3,6 @@ export { ReactWebChat as default } from '../actual/minimal'; // export * does no // #region Backward compatibility // Web devs should move to named exports instead. -// Keep types out of these namespaces until rollup-plugin-dts (used by tsup) emits types imported from another package as types: -// it emits them as `declare const X: typeof X`, which fails type checking (TS2693). Entry points export them instead, e.g. `./decorator.ts`. export * as Components from '../actual/component/minimal'; export * as decorator from '../actual/decorator'; export * as hooks from '../actual/hook/minimal'; diff --git a/packages/component/tsdown.config.mts b/packages/component/tsdown.config.mts index 5bc4b79e91..123987411e 100644 --- a/packages/component/tsdown.config.mts +++ b/packages/component/tsdown.config.mts @@ -11,8 +11,8 @@ function withPackageOptions(config: Config, moduleFormat: string): Partial - -/* eslint-env node */ -/* eslint-disable no-console */ -/* eslint-disable no-magic-numbers */ -/* eslint-disable no-restricted-globals */ - -import { injectCSSPlugin } from '@msinternal/botframework-webchat-styles/build'; -import { build, context } from 'esbuild'; -import { mkdir, writeFile } from 'fs/promises'; -import { dirname, resolve } from 'path'; -import { fileURLToPath } from 'url'; -import { cssPlugin } from '../../esbuildPlugins.mjs'; - -// TODO: [P0] We cannot import TypeScript file here. -const fluentStyleContentPlaceholder = '@--FLUENT-STYLES-CONTENT--@'; - -function createWatcherPlugin(name) { - /** @type { import('esbuild').Plugin } */ - return { - name: 'watcher', - setup(build) { - let buildStart = Date.now(); - - console.log([name, `Running in watch mode`].filter(Boolean).join(' ')); - - build.onStart(() => { - buildStart = Date.now(); - console.log([name, `Build start`].filter(Boolean).join(' ')); - }); - - build.onEnd(() => - console.log([name, `⚡ Build success in ${Date.now() - buildStart}ms`].filter(Boolean).join(' ')) - ); - } - }; -} - -/** @type { import('esbuild').BuildOptions } */ -const config = { - alias: { - 'html-react-parser': '@msinternal/html-react-parser' - }, - bundle: true, - chunkNames: `botframework-webchat-fluent-theme.[name]-[hash]`, - entryNames: `[name]`, - entryPoints: { - 'botframework-webchat-fluent-theme': './src/index.ts' - }, - external: ['botframework-webchat*', 'react', 'react-dom'], - format: 'esm', - loader: { '.js': 'jsx' }, - minify: true, - metafile: true, - outdir: resolve(fileURLToPath(import.meta.url), `../static/`), - platform: 'browser', - plugins: [ - cssPlugin, - injectCSSPlugin({ stylesPlaceholder: fluentStyleContentPlaceholder }), - { - // `write` is set to `false`, we need to emit files ourselves. - name: 'emit-output', - setup(build) { - build.onEnd(async args => { - await Promise.all( - args.outputFiles.map(async entry => { - // eslint-disable-next-line security/detect-non-literal-fs-filename - await mkdir(dirname(entry.path), { recursive: true }); - - // eslint-disable-next-line security/detect-non-literal-fs-filename - await writeFile(entry.path, entry.contents); - }) - ); - }); - } - } - ], - sourcemap: true, - splitting: true, - target: ['chrome100', 'firefox100', 'safari15'], - // Set write to false for the `injectCSSPlugin` to work. - // We will emit the output in another plugin. - write: false -}; - -(async () => { - const [_0, _1, watch] = process.argv; - - if (watch === '--watch') { - config.plugins.push(createWatcherPlugin()); - - await (await context(config)).watch({ delay: 200 }); - } else { - await build(config); - } -})(); diff --git a/packages/fluent-theme/package.json b/packages/fluent-theme/package.json index b9d3956df4..a7e9e251c5 100644 --- a/packages/fluent-theme/package.json +++ b/packages/fluent-theme/package.json @@ -51,7 +51,7 @@ "build:pre:local-dependencies": "../../scripts/npm/build-local-dependencies.sh", "build:pre:watch": "../../scripts/npm/build-watch.sh", "build:run": "concurrently --prefix-colors \"auto\" \"npm:build:run:*\"", - "build:run:static": "node ./esbuild.static.mjs", + "build:run:static": "node ./rolldown.static.mjs", "build:run:tsdown": "tsdown", "bump": "vg bump prod && vg bump dev && (npm audit fix || exit 0)", "eslint": "npm run precommit", @@ -84,6 +84,7 @@ "@types/node": "^25.9.1", "@types/react": "^16.14.70", "concurrently": "^10.0.6", + "rolldown": "~1.3.0", "tsdown": "^0.23.7", "typescript": "^6.0.3" }, diff --git a/packages/fluent-theme/rolldown.static.mjs b/packages/fluent-theme/rolldown.static.mjs new file mode 100644 index 0000000000..a0d15e4b16 --- /dev/null +++ b/packages/fluent-theme/rolldown.static.mjs @@ -0,0 +1,41 @@ +/// + +/* eslint-env node */ +/* eslint-disable no-restricted-globals */ + +import { injectCSSRolldownPlugin } from '@msinternal/botframework-webchat-styles/build'; +import { resolve } from 'path'; +import { build } from 'rolldown'; +import { fileURLToPath } from 'url'; +import { cssPlugin, inputSourceMapPlugin } from '../../rolldownPlugins.mjs'; + +// TODO: [P0] We cannot import TypeScript file here. +const fluentStyleContentPlaceholder = '@--FLUENT-STYLES-CONTENT--@'; + +const target = ['chrome100', 'firefox100', 'safari15']; + +build({ + checks: { pluginTimings: false }, + external: /^(?:botframework-webchat|react(?:-dom)?(?:\/|$))/u, + input: { 'botframework-webchat-fluent-theme': './src/index.ts' }, + moduleTypes: { '.js': 'jsx' }, + output: { + chunkFileNames: 'botframework-webchat-fluent-theme.chunk-[hash].js', + // Minified: legal comments only, rolldown keeps annotations and JSDoc by default. + comments: { annotation: false, jsdoc: false, legal: true }, + dir: resolve(fileURLToPath(import.meta.url), '../static/'), + format: 'esm', + minify: true, + sourcemap: true + }, + platform: 'browser', + plugins: [ + cssPlugin({ minify: true, target }), + inputSourceMapPlugin(), + injectCSSRolldownPlugin({ stylesPlaceholder: fluentStyleContentPlaceholder }) + ], + resolve: { alias: { 'html-react-parser': '@msinternal/html-react-parser' } }, + // Browsers have no `process`: React and other packages read `process.env.NODE_ENV` to pick their production code. + transform: { define: { 'process.env.NODE_ENV': '"production"' }, target }, + tsconfig: './src/tsconfig.json' +}); diff --git a/packages/store/package.json b/packages/store/package.json index f8fd622521..cbf0ede67e 100644 --- a/packages/store/package.json +++ b/packages/store/package.json @@ -21,7 +21,7 @@ "benchmark:json": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON ./src/benchmark.json.ts", "benchmark:node": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON ./src/benchmark.node.ts", "build": "npm run build:run", - "build:run": "tsup", + "build:run": "tsdown", "precommit": "npm run precommit:eslint -- src && npm run precommit:typecheck", "precommit:eslint": "../../node_modules/.bin/eslint --report-unused-disable-directives --max-warnings 0", "precommit:typecheck": "tsc --project ./src --emitDeclarationOnly false --esModuleInterop true --noEmit --pretty false", diff --git a/packages/store/tsdown.config.mts b/packages/store/tsdown.config.mts new file mode 100644 index 0000000000..70cd10f5b5 --- /dev/null +++ b/packages/store/tsdown.config.mts @@ -0,0 +1,5 @@ +import { defineConfig } from 'tsdown'; + +import { createDualFormatConfigs } from '../../tsdown.base.config.mts'; + +export default defineConfig(createDualFormatConfigs({ 'botframework-webchat-store': './src/index.ts' })); diff --git a/packages/store/tsup.config.ts b/packages/store/tsup.config.ts deleted file mode 100644 index 6c5a73d9a7..0000000000 --- a/packages/store/tsup.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { defineConfig } from 'tsup'; - -import { applyConfig } from '../../tsup.base.config'; - -const commonConfig = applyConfig(config => ({ - ...config, - entry: { - 'botframework-webchat-store': './src/index.ts' - } -})); - -export default defineConfig([ - { - ...commonConfig, - define: { - ...commonConfig.define, - 'globalThis.WEB_CHAT_BUILD_INFO_MODULE_FORMAT': '"esmodules"' - }, - format: 'esm', - onSuccess: 'touch ./package.json' - }, - { - ...commonConfig, - define: { - ...commonConfig.define, - 'globalThis.WEB_CHAT_BUILD_INFO_MODULE_FORMAT': '"commonjs"' - }, - format: 'cjs', - target: [...commonConfig.target, 'es2019'] - } -]); diff --git a/packages/styles/package.json b/packages/styles/package.json index 7e3363b2dc..eb96ffd597 100644 --- a/packages/styles/package.json +++ b/packages/styles/package.json @@ -82,11 +82,11 @@ }, "devDependencies": { "@jridgewell/sourcemap-codec": "^1.5.5", + "@jridgewell/trace-mapping": "^0.3.29", "@msinternal/botframework-webchat-base": "0.0.0-0", "@msinternal/botframework-webchat-tsconfig": "0.0.0-0", "@types/node": "^25.9.1", "cross-env": "^10.1.0", - "esbuild": "^0.28.1", "tsdown": "^0.23.7", "type-fest": "^5.6.0", "typescript": "^6.0.3" diff --git a/packages/styles/src/build/index.ts b/packages/styles/src/build/index.ts index bf1e045f14..f89b284ccd 100644 --- a/packages/styles/src/build/index.ts +++ b/packages/styles/src/build/index.ts @@ -1,2 +1 @@ -export { default as injectCSSPlugin, type InjectCSSPluginOptions } from './private/injectCSSPlugin'; -export { default as injectCSSRolldownPlugin } from './private/injectCSSRolldownPlugin'; +export { default as injectCSSRolldownPlugin, type InjectCSSPluginOptions } from './private/injectCSSRolldownPlugin'; diff --git a/packages/styles/src/build/private/injectCSSPlugin.spec.ts b/packages/styles/src/build/private/injectCSSPlugin.spec.ts deleted file mode 100644 index 48fcc9e5e9..0000000000 --- a/packages/styles/src/build/private/injectCSSPlugin.spec.ts +++ /dev/null @@ -1,128 +0,0 @@ -/// - -import * as JestGlobals from '@jest/globals'; -import { decode } from '@jridgewell/sourcemap-codec'; -import { scenario } from '@testduet/given-when-then'; -import { build, type Plugin } from 'esbuild'; - -import injectCSSPlugin from './injectCSSPlugin'; - -const PLACEHOLDER = '@--STYLES--@'; - -// Characters that JSON.stringify() escapes, so the embedded string is longer than the CSS. -const CSS = `.a::before { - content: "quote \\" and backslash \\\\"; -} - -.b { - color: red; -} -`; - -const FILES: ReadonlyMap = new Map([ - [ - 'index.js', - `import './style.css'; - -export const styleContent = '${PLACEHOLDER}'; - -export function afterTheStyles(value) { - return value + 1; -} -` - ], - ['style.css', CSS] -]); - -const virtualFilesPlugin: Plugin = { - name: 'virtual-files', - setup(pluginBuild) { - pluginBuild.onResolve({ filter: /\.(css|js)$/u }, ({ path }) => ({ - namespace: 'virtual', - path: path.replace(/^\.\//u, '') - })); - pluginBuild.onLoad({ filter: /\.(css|js)$/u, namespace: 'virtual' }, ({ path }) => ({ - contents: FILES.get(path) ?? '', - loader: path.endsWith('.css') ? 'css' : 'js' - })); - } -}; - -async function buildMinified(plugins: Plugin[], banner: string | undefined) { - const { outputFiles } = await build({ - absWorkingDir: process.cwd(), - ...(banner && { banner: { js: banner } }), - bundle: true, - entryPoints: ['index.js'], - format: 'esm', - metafile: true, - minify: true, - outdir: 'inject-css-plugin-spec', - plugins: [virtualFilesPlugin, ...plugins], - sourcemap: true, - write: false - }); - - const js = outputFiles.find(({ path }) => path.endsWith('.js'))?.text ?? ''; - const { mappings, sources }: { mappings: string; sources: readonly string[] } = JSON.parse( - outputFiles.find(({ path }) => path.endsWith('.js.map'))?.text ?? '{ "mappings": "", "sources": [] }' - ); - - return Object.freeze({ js, mappings: decode(mappings), sources }); -} - -// Original position of the first generated "return", which comes after the embedded styles. -function mapReturn({ - js, - mappings, - sources -}: { - js: string; - mappings: ReturnType; - sources: readonly string[]; -}) { - const index = js.indexOf('return'); - const before = js.slice(0, index); - const column = index - before.lastIndexOf('\n') - 1; - // The last segment that starts at or before the column, as source map consumers do. - const segment = (mappings[before.split('\n').length - 1] || []) - .filter(([generatedColumn]) => generatedColumn <= column) - .at(-1); - - return Object.freeze({ - column: segment?.[3], - line: segment?.[2] === undefined ? undefined : segment[2] + 1, - source: segment?.[1] === undefined ? undefined : sources[segment[1]] - }); -} - -scenario( - 'injectCSSPlugin', - bdd => { - for (const [description, banner] of [ - ['a minified build', undefined], - // The placeholder is not on the first line, so its column differs from its index in the file. - ['a minified build after a banner of two lines', '/* Banner */\n/* More banner */'] - ] as const) { - bdd - .given(`${description} with the CSS embedded, and one with the placeholder kept`, async () => - Object.freeze({ - embedded: await buildMinified([injectCSSPlugin({ stylesPlaceholder: PLACEHOLDER })], banner), - placeholder: await buildMinified([], banner) - }) - ) - .when('mapping the code after the styles back to the source', ({ embedded, placeholder }) => - Object.freeze({ embedded: mapReturn(embedded), placeholder: mapReturn(placeholder) }) - ) - .then('the CSS should replace the placeholder', ({ embedded }) => { - expect(embedded.js).not.toContain(PLACEHOLDER); - expect(embedded.js).toContain('color:red'); - }) - .and('should map to the same source position as without the plugin', (_, { embedded, placeholder }) => { - expect(placeholder).toEqual({ column: 2, line: 6, source: 'virtual:index.js' }); - expect(embedded).toEqual(placeholder); - }); - } - }, - JestGlobals -); diff --git a/packages/styles/src/build/private/injectCSSPlugin.ts b/packages/styles/src/build/private/injectCSSPlugin.ts deleted file mode 100644 index 43accdca39..0000000000 --- a/packages/styles/src/build/private/injectCSSPlugin.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { decode, encode } from '@jridgewell/sourcemap-codec'; -import path from 'node:path'; -import type { OutputFile, Plugin } from 'esbuild'; - -export interface InjectCSSPluginOptions { - ignoreCSSEntries?: string[]; - stylesPlaceholder: string; -} - -// Shifts the generated columns after the placeholder on its line, by how much longer the embedded string is. -// Other lines do not move: JSON.stringify() escapes line breaks. -function updateMappings(encoded: string, line: number, column: number, offset: number) { - const mappings = decode(encoded); - - for (const segment of mappings[+line] || []) { - if (segment[0] > column) { - segment[0] += offset; - } - } - - return encode(mappings); -} - -type Metafile = { - outputs: Record< - string, - { - entryPoint?: string; - imports?: Array<{ path: string; kind?: string; external?: boolean }>; - } - >; -}; - -function mapOutputsToRootOutputs(metafile: Metafile) { - const outputs = metafile.outputs || {}; - const allFiles = new Set(Object.keys(outputs)); - - const roots: string[] = []; - const graph = new Map(); - - for (const [file, meta] of Object.entries(outputs)) { - if (meta.entryPoint) { - roots.push(file); - } - - const edges: string[] = []; - const imports = meta.imports || []; - - for (const imp of imports) { - if (imp.external) { - continue; - } - - if (allFiles.has(imp.path)) { - edges.push(imp.path); - } else { - const resolved = path.posix.normalize(path.posix.resolve(path.posix.dirname(file), imp.path)); - if (allFiles.has(resolved)) { - edges.push(resolved); - } - } - } - graph.set(file, edges); - } - - roots.sort(); - - const outputToRoots = new Map>(); - - for (const file of allFiles) { - outputToRoots.set(file, new Set()); - } - - for (const root of roots) { - const stack = [root]; - const visited = new Set(); - - while (stack.length > 0) { - const node = stack.pop()!; - - if (visited.has(node)) { - continue; - } - visited.add(node); - - outputToRoots.get(node)?.add(root); - - const children = graph.get(node); - if (children) { - stack.push(...children); - } - } - } - - const result = new Map(); - for (const [file, rootSet] of outputToRoots) { - result.set(file, Object.freeze([...rootSet].sort())); - } - - return { roots, outputToRoots: result }; -} - -function findOutputKeyForFile(filePath: string, outputToRoots: Map): string | undefined { - const fp = path.normalize(filePath); - - // output keys in esbuild metafile are relative e.g. "dist/chunk-XYZ.js" - for (const outKey of outputToRoots.keys()) { - const k1 = path.normalize(outKey); // "dist/chunk-XYZ.js" - const k2 = path.normalize(path.join(path.sep, outKey)); // "/dist/chunk-XYZ.js" - if (fp.endsWith(k1) || fp.endsWith(k2)) { - return outKey; - } - } - - return undefined; -} - -export default function injectCSSPlugin({ ignoreCSSEntries, stylesPlaceholder }: InjectCSSPluginOptions): Plugin { - if (!stylesPlaceholder) { - throw new Error('inject-css-plugin: no placeholder for styles provided'); - } - - const stylesPlaceholderQuoted = JSON.stringify(stylesPlaceholder); - - const ignoreCSSEntriesSet = new Set(ignoreCSSEntries); - - return { - name: `inject-css-plugin(${stylesPlaceholder})`, - setup(build) { - build.onEnd(({ outputFiles = [], metafile }) => { - const cssFiles = outputFiles.filter(({ path }) => path.match(/(\.css)$/u)); - const jsFiles = outputFiles.filter(({ path }) => path.match(/(\.js|\.mjs)$/u)); - - const jsToCssMap = new Map( - cssFiles - .map(cssFile => { - const jsFilePath = jsFiles.find( - jsFile => jsFile.path.replace(/(\.js|\.mjs)$/u, '') === cssFile.path.replace(/(\.css)$/u, '') - )?.path; - if (!jsFilePath) { - return; - } - return [jsFilePath, cssFile] as const; - }) - .filter((entry): entry is readonly [string, OutputFile] => entry !== undefined) - ); - - if (!metafile) { - throw new Error('inject-css-plugin: metafile is required for proper CSS injection'); - } - - const { outputToRoots } = mapOutputsToRootOutputs(metafile); - - for (const file of outputFiles) { - if (file.path.match(/(\.js|\.mjs)$/u)) { - const jsText = file?.text; - - const shouldProccess = jsText?.includes(stylesPlaceholderQuoted); - - if (!shouldProccess) { - continue; - } - - const outKey = findOutputKeyForFile(file.path, outputToRoots); - const owners = (outKey && outputToRoots.get(outKey)) || []; - const cssFilesMap = new Map( - owners - ?.map(owner => { - const cssFile = jsToCssMap.get(path.join(process.cwd(), owner)); - if (!cssFile) { - return; - } - const cssKey = cssFile ? path.relative(process.cwd(), cssFile.path) : undefined; - return [cssKey, cssFile] as const; - }) - .filter((entry): entry is readonly [string, OutputFile] => entry !== undefined) - ); - - const cssCandidateKeys = new Set(cssFilesMap.keys()).difference(ignoreCSSEntriesSet); - - if (cssCandidateKeys.size !== 1) { - throw new Error( - `inject-css-plugin: unable to uniquely determine CSS for ${outKey}. Found CSS entries: \n[\n${[ - ...cssCandidateKeys - ] - .map(entry => ` '${entry}'`) - .join(',\n')}\n]\n Add the appropriate CSS file to ignoreCSSEntries to fix this issue.` - ); - } - - const cssText = cssFilesMap.get(Array.from(cssCandidateKeys).at(0)!)?.text; - - if (!cssText) { - throw new Error( - `inject-css-plugin: unable to find CSS text for ${outKey}.${ignoreCSSEntries ? '\n The following entries were ignored:\n' + ignoreCSSEntries.map(entry => ` '${entry}'`).join('\n') : ''}` - ); - } - - const index = jsText.indexOf(stylesPlaceholderQuoted); - const map = outputFiles.find(f => f.path.replace(/(\.map)$/u, '') === file.path); - const cssTextQuoted = JSON.stringify(cssText); - - const updatedJsText = [ - jsText.slice(0, index), - cssTextQuoted, - jsText.slice(index + stylesPlaceholderQuoted.length) - ].join(''); - - file.contents = Buffer.from(updatedJsText); - - // eslint-disable-next-line no-magic-numbers - if (updatedJsText.indexOf(stylesPlaceholder) !== -1) { - throw new Error(`Duplicate placeholders are not supported.\nFound ${stylesPlaceholder} in ${file.path}.`); - } - - if (map) { - const parsed = JSON.parse(map.text); - const textBefore = jsText.slice(0, index); - - parsed.mappings = updateMappings( - parsed.mappings, - textBefore.split('\n').length - 1, - index - textBefore.lastIndexOf('\n') - 1, - cssTextQuoted.length - stylesPlaceholderQuoted.length - ); - - map.contents = Buffer.from(JSON.stringify(parsed)); - } - } - } - }); - } - }; -} - -export { mapOutputsToRootOutputs, updateMappings, type Metafile }; diff --git a/packages/styles/src/build/private/injectCSSRolldownPlugin.spec.ts b/packages/styles/src/build/private/injectCSSRolldownPlugin.spec.ts index d5831c3d78..ad8175aa61 100644 --- a/packages/styles/src/build/private/injectCSSRolldownPlugin.spec.ts +++ b/packages/styles/src/build/private/injectCSSRolldownPlugin.spec.ts @@ -1,5 +1,12 @@ /// +import * as JestGlobals from '@jest/globals'; +import { encode } from '@jridgewell/sourcemap-codec'; +import { originalPositionFor, TraceMap } from '@jridgewell/trace-mapping'; +import { scenario } from '@testduet/given-when-then'; +import { join } from 'node:path'; +import type { Rolldown } from 'tsdown'; + import injectCSSRolldownPlugin from './injectCSSRolldownPlugin'; test.each(['a\\b', 'a"b', "a'b", 'a`b', 'a$b', 'a b'])( @@ -17,3 +24,113 @@ test.each(['@--COMPONENT-STYLES-CONTENT--@', '@--DECORATOR-STYLES-CONTENT--@', ' expect(() => injectCSSRolldownPlugin({ stylesPlaceholder })).not.toThrow(); } ); + +const PLACEHOLDER = '@--STYLES--@'; + +// Characters that JSON.stringify() escapes, so the embedded string is longer than the CSS. +const CSS = `.a::before { + content: "quote \\" and backslash \\\\"; +} + +.b { + color: red; +} +`; + +// A minified chunk and its source map, for this source (index.js): +// +// import './style.css'; +// +// export const styleContent = '@--STYLES--@'; +// +// export function afterTheStyles(value) { +// return value + 1; +// } +function createBundle(banner: string | undefined): Rolldown.OutputBundle { + const last = `const e="${PLACEHOLDER}";function t(n){return n+1}export{t as afterTheStyles,e as styleContent};`; + const lines = [...(banner ? banner.split('\n') : []), last]; + + // Zero-based [generated column, source, line, column] of `const`, `function`, `return`, `n+1` and `export`. + const segments: [number, number, number, number][] = [ + [0, 0, 2, 0], + [last.indexOf('function'), 0, 4, 0], + [last.indexOf('return'), 0, 5, 2], + [last.indexOf('n+1'), 0, 5, 9], + [last.indexOf('export'), 0, 2, 0] + ]; + const mappings = encode(lines.map((_, index) => (index === lines.length - 1 ? segments : []))); + + return { + 'index.css': { fileName: 'index.css', source: CSS, type: 'asset' }, + 'index.js': { + code: lines.join('\n'), + facadeModuleId: '/index.js', + fileName: 'index.js', + imports: [], + isEntry: true, + sourcemapFileName: 'index.js.map', + type: 'chunk' + }, + 'index.js.map': { + fileName: 'index.js.map', + source: JSON.stringify({ mappings, names: [], sources: ['index.js'], version: 3 }), + type: 'asset' + } + } as unknown as Rolldown.OutputBundle; +} + +function readChunk(bundle: Rolldown.OutputBundle) { + return Object.freeze({ + js: (bundle['index.js'] as Rolldown.OutputChunk).code, + map: new TraceMap((bundle['index.js.map'] as Rolldown.OutputAsset).source as string) + }); +} + +// Original position of the first generated "return", which comes after the embedded styles. +function mapReturn({ js, map }: ReturnType) { + const before = js.slice(0, js.indexOf('return')); + const { column, line, source } = originalPositionFor(map, { + column: before.length - before.lastIndexOf('\n') - 1, + line: before.split('\n').length + }); + + return Object.freeze({ column, line, source }); +} + +scenario( + 'injectCSSRolldownPlugin', + bdd => { + for (const [description, banner] of [ + ['a minified chunk', undefined], + // The placeholder is not on the first line, so its column differs from its index in the file. + ['a minified chunk after a banner of two lines', '/* Banner */\n/* More banner */'] + ] as const) { + bdd + .given(`${description} with the CSS embedded, and one with the placeholder kept`, () => { + const bundle = createBundle(banner); + const { generateBundle } = injectCSSRolldownPlugin({ stylesPlaceholder: PLACEHOLDER }); + + (generateBundle as { handler: (...args: unknown[]) => void }).handler.call( + undefined, + { dir: join(process.cwd(), 'dist') }, + bundle, + false + ); + + return Object.freeze({ embedded: readChunk(bundle), placeholder: readChunk(createBundle(banner)) }); + }) + .when('mapping the code after the styles back to the source', ({ embedded, placeholder }) => + Object.freeze({ embedded: mapReturn(embedded), placeholder: mapReturn(placeholder) }) + ) + .then('the CSS should replace the placeholder', ({ embedded }) => { + expect(embedded.js).not.toContain(PLACEHOLDER); + expect(embedded.js).toContain(`const e=${JSON.stringify(CSS)};`); + }) + .and('should map to the same source position as without the plugin', (_, { embedded, placeholder }) => { + expect(placeholder).toEqual({ column: 2, line: 6, source: 'index.js' }); + expect(embedded).toEqual(placeholder); + }); + } + }, + JestGlobals +); diff --git a/packages/styles/src/build/private/injectCSSRolldownPlugin.ts b/packages/styles/src/build/private/injectCSSRolldownPlugin.ts index 423fd3192d..047fe7c672 100644 --- a/packages/styles/src/build/private/injectCSSRolldownPlugin.ts +++ b/packages/styles/src/build/private/injectCSSRolldownPlugin.ts @@ -1,10 +1,28 @@ +import { decode, encode } from '@jridgewell/sourcemap-codec'; import path from 'node:path'; import type { Rolldown } from 'tsdown'; -import { mapOutputsToRootOutputs, updateMappings, type InjectCSSPluginOptions, type Metafile } from './injectCSSPlugin'; +export interface InjectCSSPluginOptions { + ignoreCSSEntries?: string[]; + stylesPlaceholder: string; +} + +// Shifts the generated columns after the placeholder on its line, by how much longer the embedded string is. +// Other lines do not move: JSON.stringify() escapes line breaks. +function updateMappings(encoded: string, line: number, column: number, offset: number) { + const mappings = decode(encoded); + + for (const segment of mappings[+line] || []) { + if (segment[0] > column) { + segment[0] += offset; + } + } -// Rolldown flavor of injectCSSPlugin (esbuild), with the same options and logic. rolldown has no metafile: the same graph -// is built from `chunk.imports`. It expects `.css` in the bundle, emitted by cssPlugin (/rolldownPlugins.mjs). + return encode(mappings); +} + +// Embeds the CSS of an entry (`.css`, emitted by cssPlugin in /rolldownPlugins.mjs) into the string placeholder +// of its chunk. The entries that own a chunk are the entry chunks that import it, directly or through other chunks. export default function injectCSSRolldownPlugin({ ignoreCSSEntries, stylesPlaceholder @@ -30,24 +48,28 @@ export default function injectCSSRolldownPlugin({ // After cssPlugin emitted the CSS files. order: 'post', handler({ dir = 'dist' }, bundle) { - // Same keys as esbuild's metafile (e.g. "dist/botframework-webchat-component.css"), for the same ignoreCSSEntries. + // Keys as in ignoreCSSEntries, relative to the package: "dist/botframework-webchat-component.css". const toKey = (fileName: string) => path.posix.join(path.relative(process.cwd(), dir).replaceAll('\\', '/'), fileName); const chunks = Object.values(bundle).filter((file): file is Rolldown.OutputChunk => file.type === 'chunk'); - - const metafile: Metafile = { - outputs: Object.fromEntries( - chunks.map(chunk => [ - toKey(chunk.fileName), - { - ...(chunk.isEntry && chunk.facadeModuleId ? { entryPoint: chunk.facadeModuleId } : {}), - imports: chunk.imports.map(fileName => ({ path: toKey(fileName) })) - } - ]) - ) - }; - - const { outputToRoots } = mapOutputsToRootOutputs(metafile); + const chunksByFileName = new Map(chunks.map(chunk => [chunk.fileName, chunk])); + // File names of the entry chunks that load each chunk. + const ownersByFileName = new Map>(); + + for (const { fileName: entryFileName } of chunks.filter(chunk => chunk.isEntry)) { + const stack = [entryFileName]; + + while (stack.length) { + const fileName = stack.pop()!; + const owners = ownersByFileName.get(fileName) ?? new Set(); + const imported = chunksByFileName.get(fileName); + + if (imported && !owners.has(entryFileName)) { + ownersByFileName.set(fileName, owners.add(entryFileName)); + stack.push(...imported.imports); + } + } + } for (const chunk of chunks) { const jsText = chunk.code; @@ -59,11 +81,10 @@ export default function injectCSSRolldownPlugin({ const outKey = toKey(chunk.fileName); const cssFilesMap = new Map( - (outputToRoots.get(outKey) || []).flatMap(owner => { - const cssKey = owner.replace(/\.[cm]?js$/u, '.css'); - const cssFile = bundle[path.posix.relative(toKey(''), cssKey)]; + [...(ownersByFileName.get(chunk.fileName) ?? [])].sort().flatMap(owner => { + const cssFile = bundle[owner.replace(/\.[cm]?js$/u, '.css')]; - return cssFile?.type === 'asset' ? [[cssKey, cssFile] as const] : []; + return cssFile?.type === 'asset' ? [[toKey(cssFile.fileName), cssFile] as const] : []; }) ); diff --git a/packages/styles/src/build/tsconfig.json b/packages/styles/src/build/tsconfig.json index 873eefab5c..fb7143e3bd 100644 --- a/packages/styles/src/build/tsconfig.json +++ b/packages/styles/src/build/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "ignoreDeprecations": "6.0", // Required for tsup@8.5.1 to work in typescript@6.0.3 "module": "nodenext", "moduleResolution": "nodenext", "types": ["node"] diff --git a/packages/test/web-server/tsdown.config.mts b/packages/test/web-server/tsdown.config.mts index 12f38fe9c3..ed9d4ee30e 100644 --- a/packages/test/web-server/tsdown.config.mts +++ b/packages/test/web-server/tsdown.config.mts @@ -6,7 +6,7 @@ function createConfig(entry: Record): UserConfig { return { deps: { alwaysBundle: [/^(?:compression|express|selfsigned)(?:\/|$)/u], onlyBundle: false }, entry, - // Like tsup: .js, not .cjs. + // `.js`, not `.cjs`: the container and package.json "main" load dist/index.js. fixedExtension: false, format: 'cjs', platform: 'node', diff --git a/packages/tsconfig/src/current/tsconfig.json b/packages/tsconfig/src/current/tsconfig.json index c0914a8868..3f01177e42 100644 --- a/packages/tsconfig/src/current/tsconfig.json +++ b/packages/tsconfig/src/current/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "ignoreDeprecations": "6.0", // Required for tsup@8.5.1 to work in typescript@6.0.3 "jsx": "react", "module": "ESNext", "moduleResolution": "Bundler", diff --git a/packages/tsconfig/src/legacy/tsconfig.json b/packages/tsconfig/src/legacy/tsconfig.json index c808fddff1..17217c61c4 100644 --- a/packages/tsconfig/src/legacy/tsconfig.json +++ b/packages/tsconfig/src/legacy/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "allowSyntheticDefaultImports": true, - "ignoreDeprecations": "6.0", // Required for tsup@8.5.1 to work in typescript@6.0.3 + "ignoreDeprecations": "6.0", // Required for "downlevelIteration" (api, component) in typescript@6 "jsx": "react", "module": "ESNext", "moduleResolution": "Bundler", diff --git a/packages/vibe-grep/src/rules/lightning-css.yaml b/packages/vibe-grep/src/rules/lightning-css.yaml index 7f0d2e9e40..4824342d4c 100644 --- a/packages/vibe-grep/src/rules/lightning-css.yaml +++ b/packages/vibe-grep/src/rules/lightning-css.yaml @@ -22,7 +22,7 @@ args: [dist/*.css] --- # This rule checks that the Lightning CSS plugin removed every "--webchat-preserve-reason" declaration. # The declaration keeps the class name of a rule without styles of its own (e.g. a class for themes) in the class map, -# and esbuildPlugins.mjs removes it once the class map is built, so it must not appear in the output CSS. +# and rolldownPlugins.mjs removes it once the class map is built, so it must not appear in the output CSS. id: no-preserve-reason-lightning-css language: Css @@ -31,6 +31,6 @@ rule: regex: "^--webchat-preserve-reason$" description: "Check that CSS compiled by Lightning CSS plugin has no --webchat-preserve-reason declarations" -message: "Output CSS has a --webchat-preserve-reason declaration. Check that esbuildPlugins.mjs removes it after the class map is built." +message: "Output CSS has a --webchat-preserve-reason declaration. Check that rolldownPlugins.mjs removes it after the class map is built." severity: error args: [dist/*.css] diff --git a/rolldownPlugins.mjs b/rolldownPlugins.mjs index 725fa77110..0d626af03d 100644 --- a/rolldownPlugins.mjs +++ b/rolldownPlugins.mjs @@ -1,9 +1,10 @@ -// Rolldown flavor of esbuildPlugins.mjs and esbuildBabelPluginIstanbul.ts, for tsdown.base.config.mts. +// Rolldown plugins of tsdown.base.config.mts and the static builds (packages/*/rolldown.static.mjs). import { transformAsync } from '@babel/core'; import { Features, transform } from 'lightningcss'; import { Buffer } from 'node:buffer'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import sourcemaps from 'rollup-plugin-sourcemaps2'; import lightningCssPlugin from 'unplugin-lightningcss/rolldown'; import { lightningCSSPluginOptions, removePreserveReason, sortClassMap } from './lightningCSSOptions.mjs'; @@ -122,7 +123,16 @@ function cssPlugin({ minify, target }) { } /** - * Adds istanbul coverage counters to our sources (`NODE_ENV=test`), like esbuildBabelPluginIstanbul.ts. + * Maps bundled files that have a source map (our packages' `dist`, npm packages) to their original sources: rolldown + * ignores the `//# sourceMappingURL` of its inputs. Only JavaScript: its `load` hook would also load the CSS modules + * (`*.module.css?css_module`) before unplugin-lightningcss can. + */ +function inputSourceMapPlugin() { + return sourcemaps({ include: /\.[cm]?js$/u }); +} + +/** + * Adds istanbul coverage counters to our sources (`NODE_ENV=test`). * * @returns {import('rolldown').Plugin} */ @@ -141,7 +151,7 @@ function istanbulPlugin() { order: 'pre', async handler(code, id) { const result = await transformAsync(code, { - configFile: join(fileURLToPath(import.meta.url), '../esbuildBabelPluginIstanbul.babel.config.json'), + configFile: join(fileURLToPath(import.meta.url), '../babelPluginIstanbul.config.json'), filename: id, rootMode: 'root', sourceFileName: id, @@ -159,4 +169,4 @@ function istanbulPlugin() { }; } -export { cssPlugin, istanbulPlugin }; +export { cssPlugin, inputSourceMapPlugin, istanbulPlugin }; diff --git a/tsdown.base.config.mts b/tsdown.base.config.mts index 97decee4b4..496d4ec7fb 100644 --- a/tsdown.base.config.mts +++ b/tsdown.base.config.mts @@ -1,15 +1,14 @@ import escapeStringRegexp from 'escape-string-regexp'; -import sourcemaps from 'rollup-plugin-sourcemaps2'; import { type UserConfig } from 'tsdown'; -import { cssPlugin, istanbulPlugin } from './rolldownPlugins.mjs'; +import { cssPlugin, inputSourceMapPlugin, istanbulPlugin } from './rolldownPlugins.mjs'; const env = process.env.NODE_ENV || 'development'; const { npm_package_version } = process.env; const minify = env === 'production' || env === 'test'; const TARGET = Object.freeze(['chrome100', 'firefox100', 'safari15']); -// When minified, esbuild drops annotations (`/* @__PURE__ */`) and JSDoc comments, rolldown keeps them by default. +// Minified output keeps legal comments only: rolldown keeps annotations (`/* @__PURE__ */`) and JSDoc by default. const MINIFIED_COMMENTS = Object.freeze({ annotation: false, jsdoc: false, legal: true }); type Config = UserConfig & { @@ -18,7 +17,7 @@ type Config = UserConfig & { target: string[]; }; -// Port of tsup.base.config.ts. +// Shared options of every tsdown build. function applyConfig(overrideOptions: (options: Omit) => Config): Config { return overrideOptions({ // Our cssPlugin (rolldownPlugins.mjs) compiles CSS modules. `false` turns off tsdown's CSS support: without @@ -33,21 +32,20 @@ function applyConfig(overrideOptions: (options: Omit) => Config define: 'undefined' }, deps: { - // Like tsup (rollup-plugin-dts), `.d.ts` import the types of every package instead of inlining them, even with - // `deps.alwaysBundle` (tsup `noExternal`). Packages that need them inlined run dtsroll after the build. + // `.d.ts` import the types of every package instead of inlining them, also of the packages in + // `deps.alwaysBundle`. Packages that need them inlined run dtsroll after the build. dts: { alwaysBundle: [], neverBundle: true }, - // Like tsup, a package bundles every import outside its dependencies and peerDependencies: our private packages - // (devDependencies, never published), core-js-pure in base, @jridgewell/sourcemap-codec in styles. `false` only - // turns off the tsdown hint that lists the bundled npm packages. + // A package bundles every import outside its dependencies and peerDependencies: our private packages + // (devDependencies, never published), core-js-pure in base, @jridgewell/sourcemap-codec in styles, and npm + // packages missing from package.json (e.g. handler-chain in api). `false` only turns off the tsdown hint that + // lists the bundled npm packages. onlyBundle: false }, dts: { // rolldown-plugin-dts emits declarations module by module as they load, and TypeScript 6 prints union members in // the order it created their types: 2 clean builds printed the same union differently. stableTypeOrdering (hidden // TypeScript 6.0 option) orders them like TypeScript 7 does. Remove on TypeScript 7 (always stable). - compilerOptions: { stableTypeOrdering: true }, - // tsup does not emit declaration maps. - sourcemap: false + compilerOptions: { stableTypeOrdering: true } }, env: { node_env: env, @@ -62,7 +60,6 @@ function applyConfig(overrideOptions: (options: Omit) => Config buildOptions.plugins = [buildOptions.plugins, cssPlugin({ minify: !!minify && minify !== 'dce-only', target })]; } }, - ignoreWatch: ['./dist/'], inputOptions: (options, format) => ({ ...options, // unplugin-lightningcss exports every class as `export { _x as "class-name" }`. String export names need ES2022: @@ -77,20 +74,15 @@ function applyConfig(overrideOptions: (options: Omit) => Config outputOptions: options => ({ ...options, ...(options.minify ? { comments: MINIFIED_COMMENTS } : {}), - // Like esbuild: `__esModule` in every CommonJS entry (rolldown adds it only with a default export). + // `__esModule` in every CommonJS entry, as published so far: bundlers then take a default import from + // `exports.default`. rolldown adds it only to entries with a default export. esModule: true, exports: 'named', - // Like esbuild: CommonJS output starts with "use strict". + // "use strict" at the top of CommonJS output: our sources are ES modules, which are strict without the directive. strict: true }), platform: 'browser', - plugins: [ - // Like esbuild: maps bundled files that have a source map (our packages' `dist`, npm packages) to their original - // sources. rolldown ignores the `//# sourceMappingURL` of its inputs. Only JavaScript: its `load` hook would also - // load the CSS modules (`*.module.css?css_module`) before unplugin-lightningcss can. - sourcemaps({ include: /\.[cm]?js$/u }), - ...(env === 'test' ? [istanbulPlugin()] : []) - ], + plugins: [inputSourceMapPlugin(), ...(env === 'test' ? [istanbulPlugin()] : [])], report: false, sourcemap: true, target: [...TARGET], @@ -125,11 +117,11 @@ function createDualFormatConfigs( } /** - * Options of an IIFE build, like tsup `format: 'iife'`. rolldown cannot split an IIFE: one entry per config. + * Options of an IIFE build. rolldown cannot split an IIFE: one entry per config. */ function iifeOptions(config: Config): Partial { return { - // tsup bundles every dependency into an IIFE. + // A script tag cannot import: the IIFE bundles every dependency. deps: { ...config.deps, alwaysBundle: () => true }, dts: false, format: 'iife', @@ -146,7 +138,7 @@ function iifeOptions(config: Config): Partial { }; } -/** tsup `noExternal: ['x']` also bundles "x/y", tsdown `deps.alwaysBundle: ['x']` does not. */ +/** Matches the package and its subpaths ("x", "x/y"): `deps.alwaysBundle: ['x']` matches "x" only. */ function packagePattern(name: string): RegExp { return new RegExp(`^${escapeStringRegexp(name)}(?:/|$)`, 'u'); } diff --git a/tsup.base.config.ts b/tsup.base.config.ts deleted file mode 100644 index 588d7e5742..0000000000 --- a/tsup.base.config.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { type Options } from 'tsup'; - -import { babelPlugin, defaultPredicate, type Predicate } from './esbuildBabelPluginIstanbul'; -import { cssPlugin } from './esbuildPlugins.mjs'; - -type Target = Exclude | undefined>; - -const env = process.env.NODE_ENV || 'development'; -const { npm_package_version } = process.env; -const istanbulPredicate: Predicate = args => defaultPredicate(args) && !/\.worker\.[cm]?[jt]s$/u.test(args.path); - -type EsbuildPlugin = NonNullable[number]; -const disablePlugin = (pluginName: string): EsbuildPlugin => ({ - name: `disable-plugin-${pluginName}`, - esbuildOptions: options => { - const plugin = options.plugins?.find(({ name }) => name === pluginName); - if (plugin) { - plugin.setup = () => Promise.resolve(); - } - } -}); - -function applyConfig( - overrideOptions: ( - options: Omit & { - define: Record; - esbuildPlugins: EsbuildPlugin[]; - target: Target[]; - } - ) => Options & { - define: Record; - esbuildPlugins: EsbuildPlugin[]; - target: Target[]; - } -): Options & { - define: Record; - esbuildPlugins: EsbuildPlugin[]; - target: Target[]; -} { - return overrideOptions({ - define: { - // TSD does not support define, thus we need to use `globalThis.*` instead. - 'globalThis.WEB_CHAT_BUILD_INFO_BUILD_TOOL': '"tsup"', - 'globalThis.WEB_CHAT_BUILD_INFO_MODULE_FORMAT': '"unknown"', - 'globalThis.WEB_CHAT_BUILD_INFO_VERSION': JSON.stringify(process.env.npm_package_version || '0.0.0-unknown') - }, - dts: true, - env: { - node_env: env, - NODE_ENV: env, - ...(npm_package_version ? { npm_package_version } : {}) - }, - esbuildOptions: options => { - // esbuild don't touch AMD but it also don't remove AMD glue code. - // Some of our packages prefers AMD over CJS via UMD and it also use anonymous modules. - // This combination conflict with RequireJS if it present in the system. - // We are removing AMD glue code manually, just like how Rollup does. - // Read more at https://github.com/evanw/esbuild/issues/1348. - // Also https://github.com/rollup/plugins/blob/e1a5ef99f1578eb38a8c87563cb9651db228f3bd/packages/commonjs/src/transform-commonjs.js#L328. - // Test case at /__tests__/html2/hosting/requirejs.html. - options.define = options.define || {}; - options.define.define = 'undefined'; - - options.legalComments = 'linked'; - }, - esbuildPlugins: - env === 'test' - ? [ - babelPlugin({ - // ESBuild use Go regular expressions and does not understand Unicode flag. - // eslint-disable-next-line require-unicode-regexp - filter: /\.[cm]?js$/, - loader: 'jsx', - name: 'babel-plugin-istanbul:js', - predicate: istanbulPredicate - }), - babelPlugin({ - // ESBuild use Go regular expressions and does not understand Unicode flag. - // eslint-disable-next-line require-unicode-regexp - filter: /\.jsx$/, - loader: 'jsx', - name: 'babel-plugin-istanbul:jsx', - predicate: istanbulPredicate - }), - babelPlugin({ - // ESBuild use Go regular expressions and does not understand Unicode flag. - // eslint-disable-next-line require-unicode-regexp - filter: /\.[cm]?ts$/, - loader: 'ts', - name: 'babel-plugin-istanbul:ts', - predicate: istanbulPredicate - }), - babelPlugin({ - // ESBuild use Go regular expressions and does not understand Unicode flag. - // eslint-disable-next-line require-unicode-regexp - filter: /\.tsx$/, - loader: 'tsx', - name: 'babel-plugin-istanbul:tsx', - predicate: istanbulPredicate - }), - cssPlugin - ] - : [cssPlugin], - format: 'esm', - ignoreWatch: './dist/', - loader: { '.js': 'jsx' }, - metafile: true, - minify: env === 'production' || env === 'test', - platform: 'browser', - plugins: [disablePlugin('postcss'), disablePlugin('svelte')], - sourcemap: true, - splitting: true, - target: ['chrome100', 'firefox100', 'safari15'] satisfies Target[] - }); -} - -export { applyConfig };