Skip to content

An open source alternative to Tableau. Embeddable visual analytic

fix(packaging): install styled-components for consumers (#521)

Elwynn Chen8e6fec6918dc
diff --git a/.github/workflows/auto-build.yml b/.github/workflows/auto-build.yml
index 63df11e3..09c45589 100644
--- a/.github/workflows/auto-build.yml
+++ b/.github/workflows/auto-build.yml
@@ -20,5 +20,9 @@ jobs:
run: yarn install
- name: npm package build
run: yarn workspace @kanaries/graphic-walker build
+ - name: Vite consumer smoke test
+ if: matrix.node-version == '20.x'
+ timeout-minutes: 20
+ run: yarn test:consumer
- name: Web app (playground) build
- run: yarn workspace playground build
\ No newline at end of file
+ run: yarn workspace playground build
diff --git a/package.json b/package.json
index 3e944653..f00bf332 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,7 @@
"devDependencies": {},
"scripts": {
"build": "yarn workspace @kanaries/graphic-walker build",
+ "test:consumer": "node scripts/consumer-smoke-test.mjs",
"deploy": "yarn workspace playground deploy",
"sync:datasets": "node scripts/demo-datasets.mjs"
},
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.json
index fdbe7675..cd555796 100644
--- a/packages/graphic-walker/package.json
+++ b/packages/graphic-walker/package.json
@@ -109,6 +109,7 @@
"react-resize-detector": "^12.3.0",
"react-shadow": "^20.6.0",
"rxjs": "^7.3.0",
+ "styled-components": "^6.1.19",
"tailwind-merge": "^2.2.1",
"tailwindcss": "^3.2.4",
"tailwindcss-animate": "^1.0.7",
@@ -133,11 +134,9 @@
"@types/react-beautiful-dnd": "^13.1.2",
"@types/react-color": "^3.0.6",
"@types/react-dom": "*",
- "@types/styled-components": "^5.1.26",
"@types/topojson-client": "^3.1.1",
"@vercel/analytics": "^1.6.1",
"@vitejs/plugin-react": "^3.1.0",
- "styled-components": "^6.1.19",
"ts-json-schema-generator": "^1.5.0",
"ts-patch": "^3.1.2",
"ts-xor": "^1.3.0",
@@ -147,7 +146,6 @@
},
"peerDependencies": {
"react": ">=19.0.0",
- "react-dom": ">=19.0.0",
- "styled-components": "^6.1.19"
+ "react-dom": ">=19.0.0"
}
}
diff --git a/packages/graphic-walker/vite.config.ts b/packages/graphic-walker/vite.config.ts
index f378638b..ddbae8bd 100644
--- a/packages/graphic-walker/vite.config.ts
+++ b/packages/graphic-walker/vite.config.ts
@@ -7,8 +7,10 @@ import { peerDependencies } from './package.json'
import { DEMO_DATASETS, downloadDemoDataset } from '../../scripts/demo-datasets.mjs';
+// styled-components is an externalized runtime dependency so consumer bundlers can
+// dedupe it; consumers are not required to provide it as a peer.
// @see https://styled-components.com/docs/faqs#marking-styledcomponents-as-external-in-your-package-dependencies
-const modulesNotToBundle = Object.keys(peerDependencies).concat(["react-dom/client", "react-dom/server"]);
+const modulesNotToBundle = Object.keys(peerDependencies).concat(['styled-components', 'react-dom/client', 'react-dom/server']);
const demoDatasetDownloads = new Map<string, Promise<Buffer>>();
function demoDatasetFallbackPlugin() {
diff --git a/packages/playground/package.json b/packages/playground/package.json
index 48b548d5..d314f0c9 100644
--- a/packages/playground/package.json
+++ b/packages/playground/package.json
@@ -29,7 +29,8 @@
"react-dom": "^19.2.0",
"react-router": "^6.20.0",
"react-router-dom": "^6.20.0",
- "react-syntax-highlighter": "^15.5.0"
+ "react-syntax-highlighter": "^15.5.0",
+ "styled-components": "^6.1.19"
},
"devDependencies": {
"@types/react": "^19.2.17",
diff --git a/scripts/consumer-smoke-test.mjs b/scripts/consumer-smoke-test.mjs
new file mode 100644
index 00000000..f8b7850f
--- /dev/null
+++ b/scripts/consumer-smoke-test.mjs
@@ -0,0 +1,236 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { realpathSync } from 'node:fs';
+import fs from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(scriptDir, '..');
+const packageDir = path.join(repoRoot, 'packages/graphic-walker');
+const require = createRequire(import.meta.url);
+
+function isPathInside(parentPath, childPath) {
+ const relativePath = path.relative(parentPath, childPath);
+
+ return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
+}
+
+async function run(command, args, cwd) {
+ console.log(`$ ${command} ${args.join(' ')}`);
+
+ await new Promise((resolve, reject) => {
+ const child = spawn(command, args, {
+ cwd,
+ stdio: 'inherit',
+ });
+
+ child.on('error', reject);
+ child.on('close', (code, signal) => {
+ if (code === 0) {
+ resolve();
+ return;
+ }
+
+ reject(new Error(`${command} exited with ${signal ? `signal ${signal}` : `code ${code}`}`));
+ });
+ });
+}
+
+function getYarnInvocation(args) {
+ const yarnCliPath = process.env.npm_execpath;
+ const isYarnCli = yarnCliPath && /^yarn(?:pkg)?(?:\.c?js)?$/i.test(path.basename(yarnCliPath));
+
+ if (isYarnCli) {
+ return {
+ command: process.execPath,
+ args: [yarnCliPath, ...args],
+ };
+ }
+
+ assert.notEqual(
+ process.platform,
+ 'win32',
+ 'On Windows, run this smoke test through Yarn Classic (yarn test:consumer) so its JavaScript CLI can be invoked safely.'
+ );
+
+ return {
+ command: 'yarn',
+ args,
+ };
+}
+
+async function runYarn(args, cwd) {
+ const invocation = getYarnInvocation(args);
+
+ await run(invocation.command, invocation.args, cwd);
+}
+
+async function getYarnVersion() {
+ const invocation = getYarnInvocation(['--version']);
+ let stdout = '';
+
+ await new Promise((resolve, reject) => {
+ const child = spawn(invocation.command, invocation.args, {
+ cwd: repoRoot,
+ stdio: ['ignore', 'pipe', 'inherit'],
+ });
+
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk;
+ });
+ child.on('error', reject);
+ child.on('close', (code, signal) => {
+ if (code === 0) {
+ resolve();
+ return;
+ }
+
+ reject(new Error(`${invocation.command} --version exited with ${signal ? `signal ${signal}` : `code ${code}`}`));
+ });
+ });
+
+ return stdout.trim();
+}
+
+async function assertExternalized(installedPackageDir) {
+ const [esmBundle, umdBundle] = await Promise.all([
+ fs.readFile(path.join(installedPackageDir, 'dist/graphic-walker.es.js'), 'utf8'),
+ fs.readFile(path.join(installedPackageDir, 'dist/graphic-walker.umd.js'), 'utf8'),
+ ]);
+ const umdPrelude = umdBundle.slice(0, 4096);
+
+ assert.match(esmBundle, /\bfrom\s*["']styled-components["']/, 'ESM bundle must keep styled-components external');
+ assert.match(umdPrelude, /require\(["']styled-components["']\)/, 'UMD bundle must require styled-components');
+ assert.match(umdPrelude, /define\(\[[^\]]*["']styled-components["']/, 'UMD AMD dependencies must include styled-components');
+ assert.match(
+ umdPrelude,
+ /([$_A-Za-z][$_\w]*)\.GraphicWalker=\{\},[^)]*\1\.styled(?:,|\))/,
+ 'UMD global dependencies must map styled-components to the styled global'
+ );
+
+ console.log('Verified styled-components remains external in the packed ESM and UMD bundles.');
+}
+
+export async function runConsumerSmokeTest(options = {}) {
+ const yarnVersion = await getYarnVersion();
+ const sourceManifest = JSON.parse(await fs.readFile(path.join(packageDir, 'package.json'), 'utf8'));
+ const expectedStyledComponentsRange = sourceManifest.dependencies?.['styled-components'];
+
+ assert.match(yarnVersion, /^1\./, `This smoke test requires Yarn Classic, received ${yarnVersion}`);
+ assert.equal(typeof expectedStyledComponentsRange, 'string', 'styled-components must be declared as a runtime dependency');
+ assert(expectedStyledComponentsRange.length > 0, 'styled-components runtime dependency range must not be empty');
+ console.log(`Using Yarn ${yarnVersion}.`);
+
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gw-361-'));
+
+ try {
+ const [realRepoRoot, realTempDir] = await Promise.all([fs.realpath(repoRoot), fs.realpath(tempDir)]);
+
+ assert(!isPathInside(realRepoRoot, realTempDir), `Consumer temp directory must be outside the repository: ${realTempDir}`);
+
+ const tarballPath = path.join(tempDir, 'graphic-walker.tgz');
+ const consumerDir = path.join(tempDir, 'consumer');
+ const sourceDir = path.join(consumerDir, 'src');
+ const yarnCacheDir = path.join(tempDir, 'yarn-cache');
+
+ if (options.tarballPath) {
+ const sourceTarball = path.resolve(options.tarballPath);
+ await fs.copyFile(sourceTarball, tarballPath);
+ console.log(`Using package tarball ${sourceTarball}.`);
+ } else {
+ try {
+ await Promise.all([
+ fs.access(path.join(packageDir, 'dist/graphic-walker.es.js')),
+ fs.access(path.join(packageDir, 'dist/graphic-walker.umd.js')),
+ ]);
+ } catch {
+ throw new Error('Graphic Walker build artifacts are missing. Run yarn build before yarn test:consumer.');
+ }
+
+ await runYarn(['pack', '--filename', tarballPath], packageDir);
+ }
+
+ const consumerPackage = {
+ name: 'graphic-walker-vite-consumer-smoke',
+ version: '0.0.0',
+ private: true,
+ type: 'module',
+ scripts: {
+ build: 'vite build',
+ },
+ dependencies: {
+ '@kanaries/graphic-walker': 'file:../graphic-walker.tgz',
+ react: '19.2.0',
+ 'react-dom': '19.2.0',
+ },
+ devDependencies: {
+ vite: '4.5.0',
+ },
+ };
+
+ await fs.mkdir(sourceDir, { recursive: true });
+ await Promise.all([
+ fs.writeFile(path.join(consumerDir, 'package.json'), `${JSON.stringify(consumerPackage, null, 2)}\n`),
+ fs.writeFile(
+ path.join(consumerDir, 'index.html'),
+ '<!doctype html><html><body><div id="app"></div><script type="module" src="/src/main.js"></script></body></html>\n'
+ ),
+ fs.writeFile(
+ path.join(sourceDir, 'main.js'),
+ [
+ "import * as graphicWalker from '@kanaries/graphic-walker';",
+ '',
+ "const exportCount = Object.keys(graphicWalker).length;",
+ "document.querySelector('#app').textContent = String(exportCount);",
+ "console.log('Graphic Walker export count:', exportCount);",
+ '',
+ ].join('\n')
+ ),
+ ]);
+
+ // Keep identically versioned before/after tarballs from reusing Yarn Classic's
+ // global cache during the negative-control and fixed-package runs.
+ await runYarn(['install', '--non-interactive', '--production=false', '--cache-folder', yarnCacheDir], consumerDir);
+
+ const installedPackageDir = path.join(consumerDir, 'node_modules/@kanaries/graphic-walker');
+ const installedConsumerManifest = JSON.parse(await fs.readFile(path.join(consumerDir, 'package.json'), 'utf8'));
+ assert(!installedConsumerManifest.dependencies?.['styled-components'], 'Consumer fixture must not declare styled-components');
+ assert(!installedConsumerManifest.devDependencies?.['styled-components'], 'Consumer fixture must not declare styled-components');
+ await assertExternalized(installedPackageDir);
+ await runYarn(['build'], consumerDir);
+
+ const resolvedStyledEntry = require.resolve('styled-components', {
+ paths: [installedPackageDir],
+ });
+ const [realConsumerDir, realResolvedStyledEntry] = await Promise.all([fs.realpath(consumerDir), fs.realpath(resolvedStyledEntry)]);
+
+ assert(isPathInside(realConsumerDir, realResolvedStyledEntry), `styled-components resolved outside the consumer tree: ${realResolvedStyledEntry}`);
+ assert(!isPathInside(realRepoRoot, realResolvedStyledEntry), `styled-components resolved from the repository hoist: ${realResolvedStyledEntry}`);
+
+ const installedManifest = JSON.parse(await fs.readFile(path.join(installedPackageDir, 'package.json'), 'utf8'));
+ assert.equal(
+ installedManifest.dependencies?.['styled-components'],
+ expectedStyledComponentsRange,
+ 'Packed package must preserve the source styled-components runtime dependency range'
+ );
+ assert(!installedManifest.peerDependencies?.['styled-components'], 'styled-components must not remain a peer dependency');
+
+ console.log(`Resolved styled-components from ${realResolvedStyledEntry}.`);
+ console.log('Graphic Walker Vite consumer smoke test passed.');
+ } finally {
+ await fs.rm(tempDir, { recursive: true, force: true });
+ }
+}
+
+const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
+
+if (isDirectRun) {
+ runConsumerSmokeTest({ tarballPath: process.argv[2] }).catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ });
+}
diff --git a/yarn.lock b/yarn.lock
index fb54940b..0726ca67 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1819,14 +1819,6 @@
dependencies:
"@types/unist" "^2"
-"@types/hoist-non-react-statics@*":
- version "3.3.5"
- resolved "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.5.tgz#dab7867ef789d87e2b4b0003c9d65c49cc44a494"
- integrity sha512-SbcrWzkKBw2cdwRTwQAswfpB9g9LJWfjtUeW/jvNwbhC8cpmmNYVePa+ncbUe0rGTQ7G3Ff6mYUN2VMfLVr+Sg==
- dependencies:
- "@types/react" "*"
- hoist-non-react-statics "^3.3.0"
-
"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1":
version "2.0.6"
resolved "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz#7739c232a1fee9b4d3ce8985f314c0c6d33549d7"
@@ -1972,15 +1964,6 @@
resolved "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz#6209321eb2c1712a7e7466422b8cb1fc0d9dd5d8"
integrity sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==
-"@types/styled-components@^5.1.26":
- version "5.1.30"
- resolved "https://registry.npmjs.org/@types/styled-components/-/styled-components-5.1.30.tgz#7f2b2c01245e3274083091517c7205c9ce9dd420"
- integrity sha512-xxJqw0s1myRTgrzHgG5tKHS9hK+KNhjbKMXDWlHRo9eDNVVUqf147QUGYUqwyCDkFyGr2pi1qJKFMEy0ACZb0A==
- dependencies:
- "@types/hoist-non-react-statics" "*"
- "@types/react" "*"
- csstype "^3.0.2"
-
version "4.2.5"
resolved "https://registry.yarnpkg.com/@types/stylis/-/stylis-4.2.5.tgz#1daa6456f40959d06157698a653a9ab0a70281df"
@@ -2739,11 +2722,6 @@ [email protected]:
resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81"
integrity sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==
-csstype@^3.0.2:
- version "3.1.2"
- resolved "https://registry.npmjs.org/csstype/-/csstype-3.1.2.tgz#1d4bf9d572f11c14031f0436e1c10bc1f571f50b"
- integrity sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ==
-
csstype@^3.2.2:
version "3.2.3"
resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.2.3.tgz#ec48c0f3e993e50648c86da559e2610995cf989a"
@@ -3645,13 +3623,6 @@ highlight.js@^10.4.1, highlight.js@~10.7.0:
resolved "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531"
integrity sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==
-hoist-non-react-statics@^3.3.0:
- version "3.3.2"
- resolved "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45"
- integrity sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==
- dependencies:
- react-is "^16.7.0"
-
html-escaper@^2.0.0:
version "2.0.2"
resolved "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453"
@@ -5048,7 +5019,7 @@ react-i18next@^11.18.6:
"@babel/runtime" "^7.14.5"
html-parse-stringify "^3.0.1"
-react-is@^16.13.1, react-is@^16.7.0:
+react-is@^16.13.1:
version "16.13.1"
resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==