Restructure the repo into npm workspaces so the component kit publishes as its own package, like MUI and shadcn/ui: - packages/ui: @openkhalix/tansy-ui (published), with components, stories, tests, tokens and the library build - packages/brand: private logo and catalogue data shared by both apps - apps/site: the landing page - apps/docs: Storybook The package: - MIT licence (copyright OpenKhalix) - per-component ES modules and type declarations - "use client" on component modules so they import into Next.js Server Components; helpers stay server-safe - tokens.css for Tailwind v4 apps, and a prebuilt styles.css for apps without Tailwind - lucide-react 1.x, whose types compile against current React 19 types The apps resolve the package through a "source" export condition, so they hot-reload component edits, while outside users get dist/. scripts/test-package.mjs packs the package and installs the tarball into Vite + Tailwind (strict types), plain React and Next.js apps; each must build and render correctly. Gitea workflows run CI on push and publish to npm when a vX.Y.Z tag matching the package version is pushed.
196 lines
9.7 KiB
JavaScript
196 lines
9.7 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Install the packed package into fresh apps, the way a user would, and prove
|
|
* it works. Run before publishing:
|
|
*
|
|
* npm run test:package # all scenarios
|
|
* npm run test:package -- vite # one scenario: vite | plain | next
|
|
*
|
|
* 1. vite Vite + Tailwind v4 + strict TypeScript (library types checked too).
|
|
* Must type-check, build and render without errors.
|
|
* 2. plain React without Tailwind, using only the prebuilt styles.css. The
|
|
* primary button must get its brand colour.
|
|
* 3. next Next.js App Router. A Server Component imports the components;
|
|
* `next build` must prerender it, which fails unless the component
|
|
* modules are marked "use client".
|
|
*
|
|
* Apps are created under $TMPDIR/tansy-package-test and installed from npm.
|
|
*/
|
|
import { execSync } from 'node:child_process'
|
|
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
import { createServer } from 'node:http'
|
|
import { createRequire } from 'node:module'
|
|
import { tmpdir } from 'node:os'
|
|
import { dirname, extname, join, resolve } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
|
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
const PKG_DIR = join(ROOT, 'packages/ui')
|
|
const WORK = join(tmpdir(), 'tansy-package-test')
|
|
const only = process.argv[2]
|
|
const require = createRequire(import.meta.url)
|
|
|
|
const sh = (cmd, cwd) => execSync(cmd, { cwd, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' })
|
|
const write = (dir, files) => {
|
|
for (const [path, content] of Object.entries(files)) {
|
|
mkdirSync(dirname(join(dir, path)), { recursive: true })
|
|
writeFileSync(join(dir, path), content.trimStart())
|
|
}
|
|
}
|
|
const log = (msg) => console.log(`[test:package] ${msg}`)
|
|
|
|
// --- pack ---------------------------------------------------------------------
|
|
rmSync(WORK, { recursive: true, force: true })
|
|
mkdirSync(WORK, { recursive: true })
|
|
log('building and packing @openkhalix/tansy-ui')
|
|
sh('npm run build', PKG_DIR)
|
|
const tarball = join(WORK, sh(`npm pack --pack-destination ${WORK}`, PKG_DIR).trim().split('\n').pop())
|
|
const { version } = JSON.parse(readFileSync(join(PKG_DIR, 'package.json'), 'utf8'))
|
|
log(`packed ${tarball}`)
|
|
|
|
const APP = `
|
|
import { Mail } from 'lucide-react'
|
|
import { Badge, Button, Dialog, FeaturedInput, Select, Tabs, VERSION } from '@openkhalix/tansy-ui'
|
|
|
|
export function Demo() {
|
|
return (
|
|
<div style={{ display: 'grid', gap: 16, maxWidth: 420, padding: 24 }}>
|
|
<Badge color="success">tansy {VERSION}</Badge>
|
|
<FeaturedInput label="Work email" startIcon={<Mail />} />
|
|
<Select label="Team" defaultValue="design" options={[{ value: 'design', label: 'Design' }, { value: 'eng', label: 'Engineering' }]} />
|
|
<Tabs label="Sections" items={[{ value: 'a', label: 'Overview', content: 'Overview panel' }, { value: 'b', label: 'Activity', content: 'Activity panel' }]} />
|
|
<Button id="primary-button">Save</Button>
|
|
<Dialog defaultOpen title="Installed from npm" footer={<Button>OK</Button>}>It works.</Dialog>
|
|
</div>
|
|
)
|
|
}
|
|
`
|
|
|
|
const VITE_BASE = {
|
|
'index.html': `<!doctype html><html><head><meta charset="UTF-8"/><title>t</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>`,
|
|
'src/Demo.tsx': APP,
|
|
'tsconfig.json': JSON.stringify({
|
|
compilerOptions: {
|
|
target: 'es2022', module: 'esnext', moduleResolution: 'bundler', jsx: 'react-jsx',
|
|
strict: true, skipLibCheck: false, noEmit: true, types: ['vite/client'],
|
|
},
|
|
include: ['src'],
|
|
}),
|
|
}
|
|
|
|
const scenarios = {
|
|
vite: {
|
|
files: {
|
|
...VITE_BASE,
|
|
'package.json': JSON.stringify({ name: 'vite-tailwind', private: true, type: 'module', scripts: { build: 'tsc && vite build' } }),
|
|
'vite.config.ts': `import react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\nimport { defineConfig } from 'vite'\nexport default defineConfig({ plugins: [react(), tailwindcss()] })\n`,
|
|
'src/app.css': `@import "tailwindcss";\n@import "@openkhalix/tansy-ui/tokens.css";\n@source "../node_modules/@openkhalix/tansy-ui/dist";\n`,
|
|
'src/main.tsx': `import { createRoot } from 'react-dom/client'\nimport { Demo } from './Demo'\nimport './app.css'\ncreateRoot(document.getElementById('root')!).render(<Demo />)\n`,
|
|
},
|
|
deps: 'react@19 react-dom@19 lucide-react vite@8 @vitejs/plugin-react tailwindcss@4 @tailwindcss/vite@4 typescript @types/react @types/react-dom',
|
|
build: 'npm run build',
|
|
serve: 'dist',
|
|
},
|
|
plain: {
|
|
files: {
|
|
...VITE_BASE,
|
|
'package.json': JSON.stringify({ name: 'plain-react', private: true, type: 'module', scripts: { build: 'tsc && vite build' } }),
|
|
'vite.config.ts': `import react from '@vitejs/plugin-react'\nimport { defineConfig } from 'vite'\nexport default defineConfig({ plugins: [react()] })\n`,
|
|
'src/main.tsx': `import { createRoot } from 'react-dom/client'\nimport '@openkhalix/tansy-ui/styles.css'\nimport { Demo } from './Demo'\ncreateRoot(document.getElementById('root')!).render(<Demo />)\n`,
|
|
},
|
|
deps: 'react@19 react-dom@19 lucide-react vite@8 @vitejs/plugin-react typescript @types/react @types/react-dom',
|
|
build: 'npm run build',
|
|
serve: 'dist',
|
|
},
|
|
next: {
|
|
files: {
|
|
'package.json': JSON.stringify({ name: 'next-app', private: true, scripts: { build: 'next build' } }),
|
|
'next.config.mjs': 'export default {}\n',
|
|
'tsconfig.json': JSON.stringify({
|
|
compilerOptions: {
|
|
target: 'es2022', lib: ['dom', 'dom.iterable', 'esnext'], strict: true, noEmit: true, module: 'esnext',
|
|
moduleResolution: 'bundler', jsx: 'react-jsx', skipLibCheck: true, isolatedModules: true, incremental: true,
|
|
plugins: [{ name: 'next' }],
|
|
},
|
|
include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],
|
|
}),
|
|
'app/layout.tsx': `import '@openkhalix/tansy-ui/styles.css'\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return <html lang="en"><body>{children}</body></html>\n}\n`,
|
|
// A Server Component: no "use client" here.
|
|
'app/page.tsx': `import { Badge, Button, cn } from '@openkhalix/tansy-ui'\nexport default function Page() {\n return <main className={cn('p-6')}><Badge color="success">server rendered</Badge><Button id="primary-button">Save</Button></main>\n}\n`,
|
|
},
|
|
deps: 'next@16 react@19 react-dom@19 lucide-react typescript @types/react @types/react-dom @types/node',
|
|
build: 'npm run build',
|
|
},
|
|
}
|
|
|
|
// --- run ------------------------------------------------------------------------
|
|
const results = []
|
|
for (const [name, s] of Object.entries(scenarios)) {
|
|
if (only && only !== name) continue
|
|
const dir = join(WORK, name)
|
|
write(dir, s.files)
|
|
try {
|
|
log(`${name}: installing`)
|
|
sh(`npm install --no-audit --no-fund ${s.deps} ${tarball}`, dir)
|
|
log(`${name}: building`)
|
|
const out = sh(s.build, dir)
|
|
if (name === 'next' && !/[○●ƒ]\s+\//.test(out)) throw new Error('next build did not report the / route')
|
|
if (s.serve) await renderCheck(name, join(dir, s.serve))
|
|
results.push([name, 'pass'])
|
|
} catch (e) {
|
|
const detail = String(e.stdout || '') + String(e.stderr || '') || e.message
|
|
results.push([name, 'FAIL', detail.split('\n').filter(Boolean).slice(-15).join('\n')])
|
|
}
|
|
}
|
|
|
|
console.log(`\n@openkhalix/tansy-ui@${version} install tests`)
|
|
for (const [name, status, detail] of results) {
|
|
console.log(` ${status === 'pass' ? '✓' : '✗'} ${name}`)
|
|
if (detail) console.log(detail.replace(/^/gm, ' '))
|
|
}
|
|
process.exit(results.some((r) => r[1] !== 'pass') ? 1 : 0)
|
|
|
|
/** Serve a built app, open it in Chrome, and check it rendered and is styled. */
|
|
async function renderCheck(name, dir) {
|
|
const types = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' }
|
|
const server = createServer((req, res) => {
|
|
const path = new URL(req.url, 'http://x').pathname
|
|
try {
|
|
const body = readFileSync(join(dir, path === '/' ? 'index.html' : path))
|
|
res.writeHead(200, { 'content-type': types[extname(path)] ?? 'text/html' })
|
|
res.end(body)
|
|
} catch {
|
|
res.writeHead(404)
|
|
res.end()
|
|
}
|
|
})
|
|
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
|
|
const { chromium } = require('playwright')
|
|
const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? '/usr/bin/google-chrome' })
|
|
try {
|
|
const page = await browser.newPage()
|
|
const errors = []
|
|
page.on('pageerror', (e) => errors.push(e.message))
|
|
await page.goto(`http://127.0.0.1:${server.address().port}/`, { waitUntil: 'networkidle' })
|
|
await page.getByRole('dialog', { name: 'Installed from npm' }).waitFor({ timeout: 10000 })
|
|
const look = await page.evaluate(() => {
|
|
const button = getComputedStyle(document.getElementById('primary-button'))
|
|
const tab = getComputedStyle(document.querySelector('[role="tab"]'))
|
|
return { bg: button.backgroundColor, text: button.color, tabBorder: tab.borderTopWidth, tabBg: tab.backgroundColor }
|
|
})
|
|
await page.screenshot({ path: join(WORK, `${name}.png`) })
|
|
if (errors.length) throw new Error(`page errors: ${errors.join('; ')}`)
|
|
// Classic Blue primary-500 (#305ddd) with white text, and tabs without the
|
|
// browser's default button chrome: proves utilities and reset both applied.
|
|
const problems = []
|
|
if (look.bg !== 'rgb(48, 93, 221)') problems.push(`button background ${look.bg}`)
|
|
if (look.text !== 'rgb(255, 255, 255)') problems.push(`button text ${look.text}`)
|
|
if (look.tabBorder !== '0px') problems.push(`tab border ${look.tabBorder}`)
|
|
if (!/rgba\(0, 0, 0, 0\)|transparent/.test(look.tabBg)) problems.push(`tab background ${look.tabBg}`)
|
|
if (problems.length) throw new Error(`components look wrong: ${problems.join(', ')}`)
|
|
} finally {
|
|
await browser.close()
|
|
server.close()
|
|
}
|
|
}
|