AI-native design editor. Open-source Figma alternative.
fix(packages): make packed exports runtime-safe (#665)
Danila Poyarkovc2aec9bacbba
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 117c9c37b..0b6f492fb 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -105,61 +105,13 @@ jobs:- uses: ./.github/actions/setup-bun- name: Build packages for publish- run: |- publish_packages="packages/scene-graph packages/pen packages/kiwi packages/fig packages/core packages/dom-css packages/cli packages/mcp packages/harness packages/vue"- for dir in $publish_packages; do- if [ -f "$dir/package.json" ] && node -p "require('./$dir/package.json').scripts?.build" 2>/dev/null | grep -qv undefined; then- echo "Building $dir..."- (cd "$dir" && bun run build)- fi- done+ run: bun tools/release-packages/src/cli.ts build- name: Prepare publish directories- run: |- bun tools/release-packages/src/prepare-publish-dirs.ts- find .publish -maxdepth 3 -type f | sort+ run: bun tools/release-packages/src/cli.ts prepare- - name: Pack packages for publish- run: |- mkdir -p .npm-packages- pack_if_new() {- local dir=$1- local name=$(node -p "require('./$dir/package.json').name")- local version=$(node -p "require('./$dir/package.json').version")- local publish_dir=".publish/$(basename "$dir")"- if npm view "${name}@${version}" version 2>/dev/null; then- echo "${name}@${version} already published, skipping pack"- else- (cd "$publish_dir" && npm pack --pack-destination "$root_dir/.npm-packages")- fi- }- root_dir="$PWD"- publish_packages="packages/scene-graph packages/pen packages/kiwi packages/fig packages/core packages/dom-css packages/cli packages/mcp packages/harness packages/vue"- for dir in $publish_packages; do- pack_if_new "$dir"- done- ls -la .npm-packages- for tarball in .npm-packages/open-pencil-*.tgz; do- echo "Contents of $tarball"- tar -tf "$tarball" | sed -n '1,60p' || true- done- bun tools/release-packages/src/validate-tarballs.ts-- - name: Publish packages to npm- run: |- publish_if_new() {- local dir=$1- local name=$(node -p "require('./$dir/package.json').name")- local version=$(node -p "require('./$dir/package.json').version")- if npm view "${name}@${version}" version 2>/dev/null; then- echo "${name}@${version} already published, skipping"- else- local tarball- tarball=$(cd .npm-packages && ls open-pencil-$(basename "$dir")-${version}.tgz)- npm publish "./.npm-packages/${tarball}" --access public --provenance- fi- }- publish_packages="packages/scene-graph packages/pen packages/kiwi packages/fig packages/core packages/dom-css packages/cli packages/mcp packages/harness packages/vue"- for dir in $publish_packages; do- publish_if_new "$dir"- done+ - name: Pack and validate packages for publish+ run: bun tools/release-packages/src/cli.ts pack++ - name: Publish verified packages to npm+ run: bun tools/release-packages/src/cli.ts publishdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d2c941ce1..3a145fc29 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -57,8 +57,8 @@ jobs:- name: Build publishable packagesrun: bun run build:packages- - name: Validate package exports- run: bun run check:packages+ - name: Validate installed package artifacts with Node and Bun+ run: bun run test:packages- name: Detect unused dependencies and filesrun: bun run check:depsdiff --git a/.gitignore b/.gitignoreindex dbda33a33..1497de180 100644--- a/.gitignore+++ b/.gitignore@@ -40,6 +40,8 @@ test-results/playwright-report/blob-report/storybook-static/+.publish/+.npm-packages/.vite/.turbo/diff --git a/AGENTS.md b/AGENTS.mdindex ee39d0644..e5b6a536d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -80,7 +80,7 @@ Prefer `dev:portless`, especially in worktrees. It assigns branch-specific app aFor releases, update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; move `Unreleased` into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; then tag and push `vX.Y.Z`.-`.github/workflows/build.yml` is the source of truth: `v*` tags build signed desktop artifacts, create a draft release from the exact changelog section, upload updater files, and publish the package set defined there and in `tools/release-packages/src/publish-dirs.ts`. Publishing uses prepared, validated npm tarballs—do not publish package directories manually. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it; `homebrew.yml` updates the cask on publication.+`.github/workflows/build.yml` is the source of truth: `v*` tags build signed desktop artifacts, create a draft release from the exact changelog section, upload updater files, and publish the public workspace packages discovered by `tools/package-artifacts/src/catalog.ts`. Bun source exports require the complete `src` directory in package contents; Node exports continue to use `dist`. Release preparation must preserve resolution maps. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks—do not publish package directories manually. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it; `homebrew.yml` updates the cask on publication.App/docs production workflows run on `v*` tags or `workflow_dispatch`, not ordinary `master` pushes. `ci.yml` and `heavy-tests.yml` define validation gates.@@ -120,6 +120,8 @@ Use Conventional Commits (`feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `bu## Code conventions+- Use Valibot for first-party runtime validation. Keep Zod at upstream SDK integration boundaries that require it, such as MCP tool registration; do not maintain parallel first-party schemas in both libraries.+- Put code and tests in the established owning domain; inspect nearby structure before adding files.- `bun run check:arch` enforces boundaries: use public workspace exports, keep Core framework-neutral, keep app services out of views/shared UI, and keep property-panel internals scoped to that panel.- Tests belong in `tests/e2e/**/*.spec.ts` (browser UI/visual), `tests/figma/**/*.spec.ts` (Figma automation), `tests/engine/**/*.test.ts` (engine/unit), `tests/helpers/**` (shared helpers), or an established package-local test location. Mirror source domains where practical and test behavior/contracts, not source text. Never commit temporary/profile specs.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fba862f1d..d5de20bab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -58,7 +58,7 @@- Preserve imported Figma divider-line geometry during auto-layout recomputation, preventing half-pixel shifts on save and reload.-- Make published package export conditions resolve to files included in npm tarballs.+- Resolve package imports under Node and Bun from ordinary tarballs while preserving Bun source-first workspace execution. (#663)- Use the user's home directory as the default MCP file root on Windows, avoiding the caller's unreliable working directory.- Open legacy raw `.fig` files that store the Kiwi document and thumbnail without a ZIP wrapper. (#582)- Preserve a frame's auto-layout HUG sizing mode when converting it into a component with `create_component`.diff --git a/bun.lock b/bun.lockindex d0aeceeff..3d5411984 100644--- a/bun.lock+++ b/bun.lock@@ -375,9 +375,26 @@"tools/docs": {"name": "@open-pencil/docs-tools",},+ "tools/package-artifacts": {+ "name": "@open-pencil/package-artifacts",+ "dependencies": {+ "pkg-types": "^2.3.1",+ "tinyexec": "^1.3.0",+ "valibot": "^1.4.2",+ },+ },"tools/package-quality": {"name": "@open-pencil/package-quality-tools","dependencies": {+ "@open-pencil/package-artifacts": "workspace:*",+ "citty": "^0.1.6",+ },+ },+ "tools/release-packages": {+ "name": "@open-pencil/release-packages",+ "dependencies": {+ "@open-pencil/package-artifacts": "workspace:*",+ "@open-pencil/package-quality-tools": "workspace:*","citty": "^0.1.6",},},@@ -1162,10 +1179,14 @@"@open-pencil/mcp": ["@open-pencil/mcp@workspace:packages/mcp"],+ "@open-pencil/package-artifacts": ["@open-pencil/package-artifacts@workspace:tools/package-artifacts"],+"@open-pencil/package-quality-tools": ["@open-pencil/package-quality-tools@workspace:tools/package-quality"],"@open-pencil/pen": ["@open-pencil/pen@workspace:packages/pen"],+ "@open-pencil/release-packages": ["@open-pencil/release-packages@workspace:tools/release-packages"],+"@open-pencil/scene-graph": ["@open-pencil/scene-graph@workspace:packages/scene-graph"],"@open-pencil/visual-oracle-tools": ["@open-pencil/visual-oracle-tools@workspace:tools/visual-oracles"],diff --git a/package.json b/package.jsonindex f230ac2a1..e09af10cb 100644--- a/package.json+++ b/package.json@@ -16,7 +16,9 @@"packages/harness","packages/docs","tools/docs",+ "tools/package-artifacts","tools/package-quality",+ "tools/release-packages","tools/visual-oracles"],"type": "module",@@ -62,7 +64,7 @@"test:tools": "bun tools/test.ts && bun --filter @open-pencil/harness test","test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/core/src packages/cli/src packages/dom-css/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0","test:packages": "bun tools/package-quality/src/cli.ts verify",- "build:packages": "bun --filter @open-pencil/scene-graph build && bun --filter @open-pencil/pen build && bun --filter @open-pencil/kiwi build && bun --filter @open-pencil/fig build && bun --filter @open-pencil/core build && bun --filter @open-pencil/dom-css build && bun --filter @open-pencil/vue build && bun --filter @open-pencil/mcp build && bun --filter @open-pencil/cli build && bun --filter @open-pencil/harness build",+ "build:packages": "bun tools/package-artifacts/src/build.ts","open-pencil": "bun packages/cli/src/index.ts","docs:dev": "bun --filter @open-pencil/docs dev","docs:build": "bun --filter @open-pencil/docs build",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 09790b481..db01d0be6 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -19,7 +19,8 @@},"files": ["bin",- "dist"+ "dist",+ "src"],"scripts": {"build": "bunx tsdown --config tsdown.config.ts",diff --git a/packages/core/package.json b/packages/core/package.jsonindex affda0e42..13400dc4f 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -9,6 +9,7 @@},"files": ["dist",+ "src","assets"],"type": "module",@@ -16,7 +17,7 @@"main": "./dist/index.js","types": "./dist/index.d.ts","imports": {- "#core/*": "./src/*"+ "#core/*": "./src/*.ts"},"exports": {"./package.json": "./package.json",diff --git a/packages/dom-css/package.json b/packages/dom-css/package.jsonindex 026b4ec49..28bc9fee0 100644--- a/packages/dom-css/package.json+++ b/packages/dom-css/package.json@@ -41,6 +41,7 @@"sideEffects": false,"files": ["dist",+ "src","README.md"],"scripts": {diff --git a/packages/fig/package.json b/packages/fig/package.jsonindex 34250728f..d8f7525f9 100644--- a/packages/fig/package.json+++ b/packages/fig/package.json@@ -28,6 +28,7 @@"sideEffects": false,"files": ["dist",+ "src","README.md"],"scripts": {diff --git a/packages/harness/package.json b/packages/harness/package.jsonindex a457de024..2d9c5a175 100644--- a/packages/harness/package.json+++ b/packages/harness/package.json@@ -31,7 +31,7 @@"access": "public","provenance": true},- "files": ["dist", "README.md"],+ "files": ["dist", "src", "README.md"],"dependencies": {"@ai-sdk/harness": "1.0.74","@ai-sdk/harness-pi": "1.0.76",diff --git a/packages/kiwi/package.json b/packages/kiwi/package.jsonindex 9222e6b37..751df8913 100644--- a/packages/kiwi/package.json+++ b/packages/kiwi/package.json@@ -9,6 +9,7 @@},"files": ["dist",+ "src","README.md","NOTICE"],diff --git a/packages/mcp/package.json b/packages/mcp/package.jsonindex 055545b7c..f63a08eb1 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -46,7 +46,8 @@"openpencil-mcp-http": "./dist/index.mjs"},"files": [- "dist"+ "dist",+ "src"],"scripts": {"build": "bunx tsdown --config tsdown.config.ts",diff --git a/packages/pen/package.json b/packages/pen/package.jsonindex 4081d8f88..492d0f560 100644--- a/packages/pen/package.json+++ b/packages/pen/package.json@@ -16,6 +16,7 @@"sideEffects": false,"files": ["dist",+ "src","README.md"],"scripts": {diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex 913b70bc4..cd12fe9b8 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -9,6 +9,7 @@},"files": ["dist",+ "src","README.md"],"type": "module",diff --git a/tools/package-artifacts/package.json b/tools/package-artifacts/package.jsonnew file mode 100644index 000000000..17e993c1e--- /dev/null+++ b/tools/package-artifacts/package.json@@ -0,0 +1,17 @@+{+ "name": "@open-pencil/package-artifacts",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts",+ "./tarball": "./src/tarball.ts"+ },+ "scripts": {+ "test": "bun test tests"+ },+ "dependencies": {+ "pkg-types": "^2.3.1",+ "tinyexec": "^1.3.0",+ "valibot": "^1.4.2"+ }+}diff --git a/tools/package-artifacts/src/build.ts b/tools/package-artifacts/src/build.tsnew file mode 100644index 000000000..7e9235771--- /dev/null+++ b/tools/package-artifacts/src/build.ts@@ -0,0 +1,35 @@+import { join } from 'node:path'++import type { WorkspacePackage } from './manifest/types'+import { runCommand } from './process'+import { discoverPublicPackages, orderPackagesByDependencies } from './workspace/catalog'+import { resolveWorkspaceRoot } from './workspace/root'++export interface BuildPublicPackagesOptions {+ log?: (message: string) => void+ output?: 'capture' | 'inherit'+ timeoutMs?: number+}++export async function buildPublicPackages(+ root: string,+ options: BuildPublicPackagesOptions = {}+): Promise<WorkspacePackage[]> {+ const packages = orderPackagesByDependencies(await discoverPublicPackages(root))+ for (const pkg of packages) {+ if (!pkg.manifest.scripts?.build) continue+ options.log?.(`Building ${pkg.manifest.name}`)+ await runCommand({+ command: 'bun',+ args: ['run', 'build'],+ cwd: join(root, pkg.directory),+ output: options.output ?? 'inherit',+ timeoutMs: options.timeoutMs ?? 180_000+ })+ }+ return packages+}++if (import.meta.main) {+ await buildPublicPackages(await resolveWorkspaceRoot(process.cwd()), { log: console.log })+}diff --git a/tools/package-artifacts/src/index.ts b/tools/package-artifacts/src/index.tsnew file mode 100644index 000000000..792ca801a--- /dev/null+++ b/tools/package-artifacts/src/index.ts@@ -0,0 +1,10 @@+export * from './build'+export * from './workspace/catalog'+export * from './manifest/exports'+export * from './workspace/root'+export * from './npm/registry'+export { parseJSONObject } from './json'+export * from './npm/pack'+export * from './manifest/read'+export * from './process'+export * from './manifest/types'diff --git a/tools/package-artifacts/src/json.ts b/tools/package-artifacts/src/json.tsnew file mode 100644index 000000000..6d3913603--- /dev/null+++ b/tools/package-artifacts/src/json.ts@@ -0,0 +1,20 @@+import * as v from 'valibot'++const jsonObjectSchema = v.record(v.string(), v.unknown())++export function parseJSON(text: string, context: string): unknown {+ try {+ return JSON.parse(text)+ } catch {+ throw new Error(`${context}: invalid JSON`)+ }+}++export function parseJSONObject(+ text: string,+ context: string+): v.InferOutput<typeof jsonObjectSchema> {+ const parsed = v.safeParse(jsonObjectSchema, parseJSON(text, context))+ if (!parsed.success) throw new Error(`${context}: expected an object`)+ return parsed.output+}diff --git a/tools/package-artifacts/src/manifest/exports.ts b/tools/package-artifacts/src/manifest/exports.tsnew file mode 100644index 000000000..a380164aa--- /dev/null+++ b/tools/package-artifacts/src/manifest/exports.ts@@ -0,0 +1,125 @@+import type { PackageTarget } from './schema'+import type { PackageDiagnostic, PackageManifest } from './types'++export interface ExportTarget {+ condition: string | null+ field: string+ target: string+}++function exportField(path: string[]): string {+ return path.reduce((field, segment, index) => {+ if (index === 0) return segment+ if (/^[A-Za-z_$][\w$]*$/.test(segment)) return `${field}.${segment}`+ if (/^\d+$/.test(segment)) return `${field}[${segment}]`+ return `${field}[${JSON.stringify(segment)}]`+ }, '')+}++function exportCondition(path: string[]): string | null {+ return (+ [...path]+ .reverse()+ .find(+ (segment) =>+ segment !== 'exports' &&+ segment !== 'imports' &&+ !segment.startsWith('.') &&+ !/^\d+$/.test(segment)+ ) ?? null+ )+}++export function collectExportTargets(+ value: PackageTarget | undefined,+ path: string[] = []+): ExportTarget[] {+ if (typeof value === 'string') {+ return [{ condition: exportCondition(path), field: exportField(path), target: value }]+ }+ if (Array.isArray(value)) {+ return value.flatMap((child, index) => collectExportTargets(child, [...path, String(index)]))+ }+ if (!value || typeof value !== 'object') return []+ return Object.entries(value).flatMap(([key, child]) =>+ collectExportTargets(child, [...path, key])+ )+}++export function concreteImportSpecifiers(manifest: PackageManifest): string[] {+ if (typeof manifest.exports === 'string') return [manifest.name]+ if (+ !manifest.exports ||+ typeof manifest.exports !== 'object' ||+ Array.isArray(manifest.exports)+ ) {+ return []+ }+ const keys = Object.keys(manifest.exports)+ if (!keys.some((key) => key.startsWith('.'))) return [manifest.name]+ return keys.flatMap((key) => {+ if (key === './package.json' || key.includes('*')) return []+ if (key === '.') return [manifest.name]+ return key.startsWith('./') ? [`${manifest.name}/${key.slice(2)}`] : []+ })+}++function isDeclarationPath(value: string): boolean {+ return /\.d\.[cm]?ts$/.test(value)+}++function includedByFiles(target: string, files: string[]): boolean {+ const normalized = target.replace(/^\.\//, '')+ if (normalized === 'package.json') return true+ const topLevel = normalized.split('/')[0]+ return Boolean(topLevel && files.includes(topLevel))+}++export function validateManifest(manifest: PackageManifest): PackageDiagnostic[] {+ const diagnostics: PackageDiagnostic[] = []+ const files = manifest.files ?? []+ const report = (field: string, message: string) =>+ diagnostics.push({ field, message, packageName: manifest.name })++ function validateRuntime(field: string, target: string, condition: string | null = null): void {+ if (isDeclarationPath(target)) report(field, `runtime target is a declaration file (${target})`)+ else if (/\.[cm]?tsx?$/.test(target) && condition !== 'bun') {+ report(field, `runtime target is TypeScript (${target})`)+ }+ if (target.startsWith('./src/') && condition !== 'bun') {+ report(field, `runtime target points to source (${target})`)+ }+ if (!includedByFiles(target, files)) report(field, `target is excluded by files (${target})`)+ }++ function validateTypes(field: string, target: string): void {+ if (!isDeclarationPath(target))+ report(field, `type target is not a declaration file (${target})`)+ if (target.startsWith('./src/')) report(field, `type target points to source (${target})`)+ if (!includedByFiles(target, files)) report(field, `target is excluded by files (${target})`)+ }++ if (!files.includes('dist')) report('files', 'must include dist')+ if (manifest.main) validateRuntime('main', manifest.main)+ if (manifest.types) validateTypes('types', manifest.types)+ if (typeof manifest.bin === 'string') validateRuntime('bin', manifest.bin)+ else {+ for (const [name, target] of Object.entries(manifest.bin ?? {})) {+ validateRuntime(`bin.${name}`, target)+ }+ }+ for (const entry of collectExportTargets(manifest.exports, ['exports'])) {+ if (entry.condition === 'types') validateTypes(entry.field, entry.target)+ else validateRuntime(entry.field, entry.target, entry.condition)+ }+ if (+ manifest.publishConfig &&+ ('exports' in manifest.publishConfig ||+ 'main' in manifest.publishConfig ||+ 'types' in manifest.publishConfig)+ ) {+ report('publishConfig', 'must not rewrite runtime entrypoints')+ }++ return diagnostics+}diff --git a/tools/package-artifacts/src/manifest/read.ts b/tools/package-artifacts/src/manifest/read.tsnew file mode 100644index 000000000..c72cc56f1--- /dev/null+++ b/tools/package-artifacts/src/manifest/read.ts@@ -0,0 +1,22 @@+import { readPackageJSON } from 'pkg-types'+import * as v from 'valibot'++import { parseJSONObject } from '../json'+import { packageManifestSchema } from './schema'+import type { PackageManifest } from './types'++export async function readPackageManifest(path: string): Promise<PackageManifest> {+ return validatePackageIdentity(await readPackageJSON(path), path)+}++function validatePackageIdentity(manifest: Record<string, unknown>, path: string): PackageManifest {+ const parsed = v.safeParse(packageManifestSchema, manifest)+ if (!parsed.success) {+ throw new Error(`${path}: invalid package manifest: ${v.summarize(parsed.issues)}`)+ }+ return parsed.output+}++export function parsePackageManifest(text: string, context: string): PackageManifest {+ return validatePackageIdentity(parseJSONObject(text, context), context)+}diff --git a/tools/package-artifacts/src/manifest/schema.ts b/tools/package-artifacts/src/manifest/schema.tsnew file mode 100644index 000000000..c6742f9c4--- /dev/null+++ b/tools/package-artifacts/src/manifest/schema.ts@@ -0,0 +1,51 @@+import * as v from 'valibot'++export type PackageTarget = string | null | PackageTarget[] | { [condition: string]: PackageTarget }++export const packageTargetSchema: v.GenericSchema<PackageTarget> = v.lazy(() =>+ v.union([+ v.string(),+ v.null(),+ v.array(packageTargetSchema),+ v.record(v.string(), packageTargetSchema)+ ])+)++const objectInput = v.pipe(+ v.unknown(),+ v.check(+ (value) => value !== null && typeof value === 'object' && !Array.isArray(value),+ 'Expected an object, not an array'+ )+)+const strings = v.pipe(objectInput, v.record(v.string(), v.string()))+const nonempty = v.pipe(v.string(), v.nonEmpty())++export const packageManifestSchema = v.looseObject({+ name: nonempty,+ version: nonempty,+ private: v.optional(v.boolean()),+ files: v.optional(v.array(nonempty)),+ main: v.optional(nonempty),+ types: v.optional(nonempty),+ bin: v.optional(v.union([nonempty, strings])),+ scripts: v.optional(strings),+ dependencies: v.optional(strings),+ devDependencies: v.optional(strings),+ peerDependencies: v.optional(strings),+ optionalDependencies: v.optional(strings),+ exports: v.optional(packageTargetSchema),+ imports: v.optional(v.pipe(objectInput, v.record(v.string(), packageTargetSchema))),+ publishConfig: v.optional(+ v.looseObject({+ access: v.optional(v.picklist(['public', 'restricted'])),+ provenance: v.optional(v.boolean()),+ registry: v.optional(nonempty),+ exports: v.optional(packageTargetSchema),+ imports: v.optional(v.record(v.string(), packageTargetSchema)),+ main: v.optional(nonempty),+ types: v.optional(nonempty),+ bin: v.optional(v.union([nonempty, strings]))+ })+ )+})diff --git a/tools/package-artifacts/src/manifest/types.ts b/tools/package-artifacts/src/manifest/types.tsnew file mode 100644index 000000000..30d14b552--- /dev/null+++ b/tools/package-artifacts/src/manifest/types.ts@@ -0,0 +1,16 @@+import type * as v from 'valibot'++import type { packageManifestSchema } from './schema'++export type PackageManifest = v.InferOutput<typeof packageManifestSchema>++export interface WorkspacePackage {+ directory: string+ manifest: PackageManifest+}++export interface PackageDiagnostic {+ field: string+ message: string+ packageName: string+}diff --git a/tools/package-artifacts/src/npm/pack.ts b/tools/package-artifacts/src/npm/pack.tsnew file mode 100644index 000000000..525707a7c--- /dev/null+++ b/tools/package-artifacts/src/npm/pack.ts@@ -0,0 +1,38 @@+import * as v from 'valibot'++import { parseJSON } from '../json'++function isPackageRelativePath(path: string): boolean {+ return (+ !path.startsWith('/') &&+ !path.includes('\\') &&+ !path.split('/').some((part) => part === '..' || part === '.')+ )+}++const packResultSchema = v.pipe(+ v.strictTuple([+ v.object({+ filename: v.pipe(v.string(), v.regex(/^[^/\\]+\.tgz$/)),+ files: v.array(+ v.object({+ path: v.pipe(v.string(), v.nonEmpty(), v.check(isPackageRelativePath))+ })+ )+ })+ ]),+ v.transform(([result]) => ({+ filename: result.filename,+ files: result.files.map(({ path }) => path)+ }))+)++export type NpmPackResult = v.InferOutput<typeof packResultSchema>++export function parseNpmPack(text: string): NpmPackResult {+ const parsed = v.safeParse(packResultSchema, parseJSON(text, 'npm pack'))+ if (!parsed.success) {+ throw new Error(`npm pack: invalid response: ${v.summarize(parsed.issues)}`)+ }+ return parsed.output+}diff --git a/tools/package-artifacts/src/npm/registry.ts b/tools/package-artifacts/src/npm/registry.tsnew file mode 100644index 000000000..2ddf44d8d--- /dev/null+++ b/tools/package-artifacts/src/npm/registry.ts@@ -0,0 +1,26 @@+import * as v from 'valibot'++const registryErrorSchema = v.object({ error: v.object({ code: v.string() }) })+const registryVersionSchema = v.pipe(v.string(), v.nonEmpty())++export function isRegistryNotFound(text: string): boolean {+ try {+ const parsed = v.safeParse(registryErrorSchema, JSON.parse(text))+ return parsed.success && parsed.output.error.code === 'E404'+ } catch {+ return false // Non-JSON output is not evidence that a version is absent.+ }+}++export function validateRegistryVersion(text: string, expected: string): void {+ let value: unknown+ try {+ value = JSON.parse(text)+ } catch {+ throw new Error('npm view: invalid JSON')+ }+ const parsed = v.safeParse(registryVersionSchema, value)+ if (!parsed.success || parsed.output !== expected) {+ throw new Error(`npm view: expected version ${expected}`)+ }+}diff --git a/tools/package-artifacts/src/process.ts b/tools/package-artifacts/src/process.tsnew file mode 100644index 000000000..6b5e10075--- /dev/null+++ b/tools/package-artifacts/src/process.ts@@ -0,0 +1,68 @@+import { x } from 'tinyexec'++export interface CommandRequest {+ args?: string[]+ command: string+ cwd: string+ env?: NodeJS.ProcessEnv+ output?: 'capture' | 'inherit'+ timeoutMs?: number+}++export interface CommandResult {+ stderr: string+ stdout: string+}++export class CommandError extends Error {+ constructor(+ message: string,+ readonly request: CommandRequest,+ readonly exitCode: number | null,+ readonly stdout: string,+ readonly stderr: string,+ readonly timedOut: boolean+ ) {+ super(message)+ this.name = 'CommandError'+ }+}++/** Project diagnostics only; tinyexec owns spawning, stream completion and cancellation. */+export async function runCommand(request: CommandRequest): Promise<CommandResult> {+ const deadline =+ request.timeoutMs === undefined ? undefined : AbortSignal.timeout(request.timeoutMs)+ // tinyexec distinguishes cancellation from its own timeout errors. Use cancellation+ // so completed output remains available for the project's timeout diagnostics.+ const controller = new AbortController()+ const cancel = () => controller.abort()+ deadline?.addEventListener('abort', cancel, { once: true })+ try {+ const result = x(request.command, request.args ?? [], {+ signal: controller.signal,+ nodePath: false,+ nodeOptions: {+ cwd: request.cwd,+ env: request.env,+ killSignal: 'SIGKILL',+ stdio: request.output === 'inherit' ? 'inherit' : ['ignore', 'pipe', 'pipe']+ }+ })+ const { stdout, stderr, exitCode } = await result+ const timedOut = deadline?.aborted ?? false+ if (exitCode === 0 && !timedOut) return { stdout, stderr }+ const reason = timedOut+ ? `timed out after ${request.timeoutMs}ms`+ : `exit code ${exitCode ?? result.signalCode ?? 'unknown'}`+ throw new CommandError(+ `${[request.command, ...(request.args ?? [])].join(' ')} failed: ${reason}`,+ request,+ exitCode ?? null,+ stdout,+ stderr,+ timedOut+ )+ } finally {+ deadline?.removeEventListener('abort', cancel)+ }+}diff --git a/tools/package-artifacts/src/tarball.ts b/tools/package-artifacts/src/tarball.tsnew file mode 100644index 000000000..08dc5ba2f--- /dev/null+++ b/tools/package-artifacts/src/tarball.ts@@ -0,0 +1,113 @@+import { execFile } from 'node:child_process'+import { readdir } from 'node:fs/promises'+import { join } from 'node:path'+import { promisify } from 'node:util'++import { collectExportTargets } from './manifest/exports'+import { parsePackageManifest } from './manifest/read'+import type { PackageManifest } from './manifest/types'++const execFileAsync = promisify(execFile)++export interface TarballDiagnostic {+ field: string+ message: string+ packageName: string+ tarballPath: string+}++export interface TarballInspection {+ diagnostics: TarballDiagnostic[]+ entries: Set<string>+ manifest: PackageManifest+ tarballPath: string+}++export function packageBinTargets(manifest: PackageManifest): Record<string, string> {+ if (typeof manifest.bin === 'string') return { [manifest.name]: manifest.bin }+ return manifest.bin ?? {}+}++export function packageExportTargetPaths(manifest: Pick<PackageManifest, 'exports'>): string[] {+ return collectExportTargets(manifest.exports).map(({ target }) => target)+}++export async function tarballEntries(tarballPath: string): Promise<Set<string>> {+ const { stdout } = await execFileAsync('tar', ['-tf', tarballPath], { encoding: 'utf8' })+ return new Set(stdout.trim().split('\n').filter(Boolean))+}++export async function tarballPackageJSON(tarballPath: string): Promise<PackageManifest> {+ const { stdout } = await execFileAsync('tar', ['-xOf', tarballPath, 'package/package.json'], {+ encoding: 'utf8'+ })+ return parsePackageManifest(stdout, `${tarballPath}: package/package.json`)+}++function exportTargetPattern(target: string): RegExp {+ const escaped = target.replace(/[.+?^${}()|[\]\\]/g, '\\$&')+ return new RegExp(`^${escaped.replace(/\*/g, '.*')}$`)+}++function targetExists(entries: Set<string>, target: string): boolean {+ const relativeTarget = target.replace(/^\.\//, '')+ if (relativeTarget.startsWith('/') || relativeTarget.split('/').includes('..')) return false+ if (!relativeTarget.includes('*')) return entries.has(`package/${relativeTarget}`)+ const pattern = exportTargetPattern(relativeTarget)+ return [...entries].some((entry) =>+ entry.startsWith('package/') ? pattern.test(entry.slice('package/'.length)) : false+ )+}++export async function inspectTarball(tarballPath: string): Promise<TarballInspection> {+ const [entries, manifest] = await Promise.all([+ tarballEntries(tarballPath),+ tarballPackageJSON(tarballPath)+ ])+ const diagnostics: TarballDiagnostic[] = []+ const report = (field: string, message: string) =>+ diagnostics.push({ field, message, packageName: manifest.name, tarballPath })++ for (const field of ['main', 'types'] as const) {+ const target = manifest[field]+ if (target && !targetExists(entries, target)) report(field, `target is missing (${target})`)+ }+ for (const [name, target] of Object.entries(packageBinTargets(manifest))) {+ if (!targetExists(entries, target)) report(`bin.${name}`, `target is missing (${target})`)+ }+ for (const { field, target } of collectExportTargets(manifest.exports, ['exports'])) {+ if (!targetExists(entries, target)) report(field, `target is missing (${target})`)+ }+ return { diagnostics, entries, manifest, tarballPath }+}++export async function inspectTarballDirectory(directory: string): Promise<TarballInspection[]> {+ const tarballs = (await readdir(directory))+ .filter((name) => name.endsWith('.tgz'))+ .sort()+ .map((name) => join(directory, name))+ return await Promise.all(tarballs.map(inspectTarball))+}++function formatDiagnostic(diagnostic: TarballDiagnostic): string {+ return `${diagnostic.packageName}: ${diagnostic.field} ${diagnostic.message}`+}++export async function validateTarballBinTargets(tarballPath: string): Promise<void> {+ const inspection = await inspectTarball(tarballPath)+ const diagnostics = inspection.diagnostics.filter(({ field }) => field.startsWith('bin'))+ if (diagnostics.length > 0) throw new Error(diagnostics.map(formatDiagnostic).join('\n'))+}++export async function validateTarballExportTargets(tarballPath: string): Promise<void> {+ const inspection = await inspectTarball(tarballPath)+ const diagnostics = inspection.diagnostics.filter(({ field }) => field.startsWith('exports'))+ if (diagnostics.length > 0) throw new Error(diagnostics.map(formatDiagnostic).join('\n'))+}++export async function validatePackedTarballs(directory: string): Promise<void> {+ const inspections = await inspectTarballDirectory(directory)+ if (inspections.length === 0) throw new Error(`No package tarballs found in ${directory}`)+ const diagnostics = inspections.flatMap(({ diagnostics }) => diagnostics)+ if (diagnostics.length > 0) throw new Error(diagnostics.map(formatDiagnostic).join('\n'))+}diff --git a/tools/package-artifacts/src/workspace/catalog.ts b/tools/package-artifacts/src/workspace/catalog.tsnew file mode 100644index 000000000..30e945954--- /dev/null+++ b/tools/package-artifacts/src/workspace/catalog.ts@@ -0,0 +1,59 @@+import { join } from 'node:path'++import { readPackageJSON } from 'pkg-types'++import { readPackageManifest } from '../manifest/read'+import type { PackageManifest, WorkspacePackage } from '../manifest/types'+import { parseWorkspace } from './schema'++const DEPENDENCY_FIELDS = [+ 'dependencies',+ 'peerDependencies',+ 'optionalDependencies'+] as const satisfies ReadonlyArray<keyof PackageManifest>++export async function discoverPublicPackages(root: string): Promise<WorkspacePackage[]> {+ const rootManifest = await readPackageJSON(join(root, 'package.json'))+ const packages: WorkspacePackage[] = []++ const { workspaces } = parseWorkspace(rootManifest, root)+ for (const directory of workspaces) {+ const raw = await readPackageJSON(join(root, directory, 'package.json'))+ if (raw.private === true) continue+ const manifest = await readPackageManifest(join(root, directory, 'package.json'))+ packages.push({ directory, manifest })+ }++ return packages+}++export function orderPackagesByDependencies(packages: WorkspacePackage[]): WorkspacePackage[] {+ const packageByName = new Map(packages.map((pkg) => [pkg.manifest.name, pkg]))+ const permanent = new Set<string>()+ const temporary = new Set<string>()+ const ordered: WorkspacePackage[] = []++ function visit(pkg: WorkspacePackage, path: string[]): void {+ const name = pkg.manifest.name+ if (permanent.has(name)) return+ if (temporary.has(name)) {+ throw new Error(`Workspace dependency cycle: ${[...path, name].join(' -> ')}`)+ }++ temporary.add(name)+ for (const field of DEPENDENCY_FIELDS) {+ const dependencies = pkg.manifest[field]+ if (!dependencies) continue+ for (const dependencyName of Object.keys(dependencies).sort()) {+ const dependency = packageByName.get(dependencyName)+ if (dependency) visit(dependency, [...path, name])+ }+ }+ temporary.delete(name)+ permanent.add(name)+ ordered.push(pkg)+ }++ for (const pkg of packages) visit(pkg, [])+ return ordered+}diff --git a/tools/package-artifacts/src/workspace/root.ts b/tools/package-artifacts/src/workspace/root.tsnew file mode 100644index 000000000..d0fdb90c9--- /dev/null+++ b/tools/package-artifacts/src/workspace/root.ts@@ -0,0 +1,15 @@+import { join, resolve } from 'node:path'++import { findWorkspaceDir, readPackageJSON } from 'pkg-types'++import { parseWorkspace } from './schema'++/** Resolve once at CLI boundaries; nearest lockfile keeps nested Git worktrees isolated. */+export async function resolveWorkspaceRoot(start: string, explicitRoot?: string): Promise<string> {+ const root = explicitRoot+ ? resolve(start, explicitRoot)+ : await findWorkspaceDir(start, { tests: ['lockFile'], lockFile: 'closest' })+ const manifest = await readPackageJSON(join(root, 'package.json'))+ parseWorkspace(manifest, root)+ return root+}diff --git a/tools/package-artifacts/src/workspace/schema.ts b/tools/package-artifacts/src/workspace/schema.tsnew file mode 100644index 000000000..e1b36e90d--- /dev/null+++ b/tools/package-artifacts/src/workspace/schema.ts@@ -0,0 +1,27 @@+import * as v from 'valibot'+const nonempty = v.pipe(v.string(), v.nonEmpty())++// This repository deliberately declares literal workspace directories, not glob patterns.+const directory = v.pipe(+ nonempty,+ v.check(+ (path) =>+ !path.startsWith('/') &&+ !/[\\*?[\]{}]/.test(path) &&+ !path.split('/').some((part) => part === '..' || part === '.' || !part)+ )+)++export const workspaceSchema = v.looseObject({+ workspaces: v.pipe(v.array(directory), v.nonEmpty())+})++export function parseWorkspace(+ value: unknown,+ context: string+): v.InferOutput<typeof workspaceSchema> {+ const parsed = v.safeParse(workspaceSchema, value)+ if (!parsed.success)+ throw new Error(`${context}: expected a workspace manifest: ${v.summarize(parsed.issues)}`)+ return parsed.output+}diff --git a/tools/package-artifacts/tests/catalog.test.ts b/tools/package-artifacts/tests/catalog.test.tsnew file mode 100644index 000000000..bbddbe386--- /dev/null+++ b/tools/package-artifacts/tests/catalog.test.ts@@ -0,0 +1,67 @@+import { describe, expect, test } from 'bun:test'+import { mkdir, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import type { WorkspacePackage } from '../src/manifest/types'+import { discoverPublicPackages, orderPackagesByDependencies } from '../src/workspace/catalog'++function pkg(name: string, dependencies: Record<string, string> = {}): WorkspacePackage {+ return { directory: `packages/${name}`, manifest: { name, version: '1.0.0', dependencies } }+}++describe('discoverPublicPackages', () => {+ test('discovers public workspaces and excludes private tooling', async () => {+ const root = join(tmpdir(), `open-pencil-package-catalog-${crypto.randomUUID()}`)+ await mkdir(join(root, 'packages/public'), { recursive: true })+ await mkdir(join(root, 'tools/private'), { recursive: true })+ await writeFile(+ join(root, 'package.json'),+ JSON.stringify({ workspaces: ['packages/public', 'tools/private'] })+ )+ await writeFile(+ join(root, 'packages/public/package.json'),+ JSON.stringify({ name: '@fixture/public', version: '1.0.0' })+ )+ await writeFile(+ join(root, 'tools/private/package.json'),+ JSON.stringify({ name: '@fixture/private', version: '1.0.0', private: true })+ )++ expect(await discoverPublicPackages(root)).toEqual([+ {+ directory: 'packages/public',+ manifest: { name: '@fixture/public', version: '1.0.0' }+ }+ ])+ })+})++describe('orderPackagesByDependencies', () => {+ test('orders internal dependencies before their consumers', () => {+ const ordered = orderPackagesByDependencies([+ pkg('app', { library: 'workspace:*' }),+ pkg('library')+ ])+ expect(ordered.map(({ manifest }) => manifest.name)).toEqual(['library', 'app'])+ })++ test('orders a diamond dependency graph once and stably', () => {+ const ordered = orderPackagesByDependencies([+ pkg('app', { left: 'workspace:*', right: 'workspace:*' }),+ pkg('left', { base: 'workspace:*' }),+ pkg('right', { base: 'workspace:*' }),+ pkg('base')+ ])+ expect(ordered.map(({ manifest }) => manifest.name)).toEqual(['base', 'left', 'right', 'app'])+ })++ test('reports dependency cycles', () => {+ expect(() =>+ orderPackagesByDependencies([+ pkg('one', { two: 'workspace:*' }),+ pkg('two', { one: 'workspace:*' })+ ])+ ).toThrow('Workspace dependency cycle: one -> two -> one')+ })+})diff --git a/tools/package-artifacts/tests/exports.test.ts b/tools/package-artifacts/tests/exports.test.tsnew file mode 100644index 000000000..a5e1db49b--- /dev/null+++ b/tools/package-artifacts/tests/exports.test.ts@@ -0,0 +1,61 @@+import { describe, expect, test } from 'bun:test'++import {+ collectExportTargets,+ concreteImportSpecifiers,+ validateManifest+} from '../src/manifest/exports'+import type { PackageManifest } from '../src/manifest/types'++const validManifest: PackageManifest = {+ name: '@open-pencil/example',+ version: '1.0.0',+ files: ['dist'],+ exports: {+ '.': {+ types: './dist/index.d.ts',+ bun: './dist/index.js',+ import: './dist/index.js'+ },+ './feature': { import: './dist/feature.js' },+ './pattern/*': { import: './dist/*.js' },+ './package.json': './package.json'+ }+}++describe('export metadata', () => {+ test('collects conditional targets with their fields', () => {+ expect(collectExportTargets(validManifest.exports, ['exports'])).toContainEqual({+ condition: 'bun',+ field: 'exports["."].bun',+ target: './dist/index.js'+ })+ })++ test('derives only concrete public import specifiers', () => {+ expect(concreteImportSpecifiers(validManifest)).toEqual([+ '@open-pencil/example',+ '@open-pencil/example/feature'+ ])+ })++ test('accepts pack-safe runtime targets', () => {+ expect(validateManifest(validManifest)).toEqual([])+ })++ test('rejects source bun targets and runtime declarations', () => {+ const diagnostics = validateManifest({+ ...validManifest,+ exports: {+ '.': {+ bun: './src/index.ts',+ import: './dist/index.d.ts'+ }+ }+ })+ expect(diagnostics.map(({ message }) => message)).toEqual([+ 'target is excluded by files (./src/index.ts)',+ 'runtime target is a declaration file (./dist/index.d.ts)'+ ])+ })+})diff --git a/tools/package-artifacts/tests/npm-output.test.ts b/tools/package-artifacts/tests/npm-output.test.tsnew file mode 100644index 000000000..e9855c2e4--- /dev/null+++ b/tools/package-artifacts/tests/npm-output.test.ts@@ -0,0 +1,48 @@+import { expect, test } from 'bun:test'++import { parsePackageManifest } from '../src/manifest/read'+import { parseNpmPack } from '../src/npm/pack'++test('npm pack parser validates archive names and paths', () => {+ expect(+ parseNpmPack(JSON.stringify([{ filename: 'pkg.tgz', files: [{ path: 'src/index.ts' }] }]))+ ).toEqual({ filename: 'pkg.tgz', files: ['src/index.ts'] })+ for (const value of [+ null,+ [],+ [+ { filename: 'a.tgz', files: [] },+ { filename: 'b.tgz', files: [] }+ ],+ [{ filename: 42, files: [] }],+ [{ filename: 'pkg.tgz', files: [{ path: '' }] }],+ [{ filename: 'pkg.tgz', files: [{ path: '/absolute' }] }],+ [{ filename: 'pkg.tgz', files: [{ path: 'src\\\\index.ts' }] }],+ [{ filename: '../pkg.tgz', files: [] }],+ [{ filename: 'pkg.tgz', files: [{ path: '../outside' }] }]+ ]) {+ expect(() => parseNpmPack(JSON.stringify(value))).toThrow('npm pack:')+ }+})++test('npm pack parser ignores unrelated npm fields', () => {+ expect(+ parseNpmPack(+ JSON.stringify([+ {+ filename: 'pkg.tgz',+ size: 123,+ integrity: 'sha512-example',+ files: [{ path: 'src/value.ts', size: 10, mode: 420 }]+ }+ ])+ )+ ).toEqual({ filename: 'pkg.tgz', files: ['src/value.ts'] })+})++test('tarball manifest identity errors include archive context', () => {+ expect(() => parsePackageManifest('{', 'archive.tgz')).toThrow('archive.tgz: invalid JSON')+ expect(() => parsePackageManifest('{"name":3}', 'archive.tgz')).toThrow(+ 'archive.tgz: invalid package manifest'+ )+})diff --git a/tools/package-artifacts/tests/process.test.ts b/tools/package-artifacts/tests/process.test.tsnew file mode 100644index 000000000..872884229--- /dev/null+++ b/tools/package-artifacts/tests/process.test.ts@@ -0,0 +1,61 @@+import { describe, expect, test } from 'bun:test'++import { CommandError, runCommand } from '../src/process'++describe('runCommand', () => {+ test('captures output', async () => {+ const result = await runCommand({+ command: process.execPath,+ args: ['--eval', "process.stdout.write('ready')"],+ cwd: process.cwd()+ })+ expect(result.stdout).toBe('ready')+ })++ test('captures output larger than a pipe buffer before resolving', async () => {+ const result = await runCommand({+ command: process.execPath,+ args: ['--eval', "process.stdout.write('x'.repeat(262144)); process.stderr.write('done')"],+ cwd: process.cwd(),+ timeoutMs: 10_000+ })+ expect(result.stdout).toHaveLength(262144)+ expect(result.stderr).toBe('done')+ })++ test('reports missing executables', async () => {+ await expect(+ runCommand({+ command: '/nonexistent/open-pencil-command',+ cwd: process.cwd(),+ timeoutMs: 1000+ })+ ).rejects.toThrow()+ })++ test('returns structured command failures', async () => {+ const failure = runCommand({+ command: process.execPath,+ args: ['--eval', "process.stderr.write('broken'); process.exit(7)"],+ cwd: process.cwd()+ })+ const error = await failure.catch((caught: unknown) => caught)+ expect(error).toBeInstanceOf(CommandError)+ if (!(error instanceof CommandError)) throw new Error('Expected CommandError')+ expect(error.exitCode).toBe(7)+ expect(error.stderr).toBe('broken')+ })++ test('terminates commands after their deadline', async () => {+ const error = await runCommand({+ command: process.execPath,+ args: ['--eval', 'setTimeout(() => {}, 10_000)'],+ cwd: process.cwd(),+ timeoutMs: 20+ }).catch((caught: unknown) => caught)+ expect(error).toBeInstanceOf(CommandError)+ if (!(error instanceof CommandError)) throw new Error('Expected CommandError')+ expect(error.timedOut).toBe(true)+ expect(error.message).toContain('timed out after 20ms')+ })+})diff --git a/tools/package-artifacts/tests/root.test.ts b/tools/package-artifacts/tests/root.test.tsnew file mode 100644index 000000000..4449cb280--- /dev/null+++ b/tools/package-artifacts/tests/root.test.ts@@ -0,0 +1,26 @@+import { expect, test } from 'bun:test'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { resolveWorkspaceRoot } from '../src/workspace/root'++test('nearest workspace lockfile isolates nested worktrees from the parent checkout', async () => {+ const parent = await mkdtemp(join(tmpdir(), 'workspace-root-'))+ try {+ const worktree = join(parent, '.worktrees', 'feature')+ const nested = join(worktree, 'tools', 'release')+ await mkdir(nested, { recursive: true })+ for (const root of [parent, worktree]) {+ await writeFile(join(root, 'bun.lock'), '{}')+ await writeFile(join(root, 'package.json'), JSON.stringify({ workspaces: ['tools/release'] }))+ }+ await writeFile(join(worktree, '.git'), 'gitdir: /not-needed-for-discovery')+ expect(await resolveWorkspaceRoot(nested)).toBe(worktree)+ expect(await resolveWorkspaceRoot(nested, parent)).toBe(parent)+ await writeFile(join(nested, 'package.json'), JSON.stringify({ private: true }))+ await expect(resolveWorkspaceRoot(nested, '.')).rejects.toThrow('expected a workspace manifest')+ } finally {+ await rm(parent, { recursive: true, force: true })+ }+})diff --git a/tools/package-artifacts/tests/schemas.test.ts b/tools/package-artifacts/tests/schemas.test.tsnew file mode 100644index 000000000..89ab62ab1--- /dev/null+++ b/tools/package-artifacts/tests/schemas.test.ts@@ -0,0 +1,54 @@+import { expect, test } from 'bun:test'++import { parsePackageManifest } from '../src/manifest/read'+import { isRegistryNotFound, validateRegistryVersion } from '../src/npm/registry'+import { parseWorkspace } from '../src/workspace/schema'++const identity = { name: 'fixture', version: '1.0.0' }++test('manifest boundary rejects malformed fields, including nested export targets', () => {+ for (const fields of [+ { exports: 42 },+ { exports: { '.': { bun: true } } },+ { dependencies: [] },+ { dependencies: { other: 1 } },+ { files: 'dist' },+ { bin: { cli: false } },+ { scripts: { build: 1 } },+ { imports: [] },+ { publishConfig: { provenance: 'true' } }+ ]) {+ expect(() =>+ parsePackageManifest(JSON.stringify({ ...identity, ...fields }), 'fixture.json')+ ).toThrow('fixture.json: invalid package manifest')+ }+})++test('manifest schemas preserve metadata and valid recursive export alternatives', () => {+ const manifest = {+ ...identity,+ custom: { keep: true },+ exports: {+ '.': { bun: ['./src/index.ts', null], default: './dist/index.js' },+ './private': null+ }+ }+ expect(parsePackageManifest(JSON.stringify(manifest), 'fixture')).toEqual(manifest)+})++test('workspace schema rejects unsupported or unsafe directory declarations', () => {+ for (const workspaces of [[], 'packages/*', ['packages/*'], [42], ['../outside'], ['/outside']]) {+ expect(() => parseWorkspace({ workspaces }, 'root')).toThrow(+ 'root: expected a workspace manifest'+ )+ }+})++test('registry output distinguishes missing versions from errors and malformed responses', () => {+ expect(isRegistryNotFound('{"error":{"code":"E404"}}')).toBe(true)+ for (const response of ['E404', '{', '{"error":{"code":"E401"}}', '{"error":42}']) {+ expect(isRegistryNotFound(response)).toBe(false)+ }+ expect(() => validateRegistryVersion('"1.0.0"', '1.0.0')).not.toThrow()+ expect(() => validateRegistryVersion('"2.0.0"', '1.0.0')).toThrow('expected version')+})diff --git a/tools/package-artifacts/tests/tarball.test.ts b/tools/package-artifacts/tests/tarball.test.tsnew file mode 100644index 000000000..1a8f201bb--- /dev/null+++ b/tools/package-artifacts/tests/tarball.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test } from 'bun:test'++import { packageBinTargets, packageExportTargetPaths } from '../src/tarball'++describe('tarball metadata', () => {+ test('normalizes string and named binaries', () => {+ expect(packageBinTargets({ name: 'example', version: '1', bin: './cli.js' })).toEqual({+ example: './cli.js'+ })+ expect(+ packageBinTargets({ name: 'example', version: '1', bin: { other: './other.js' } })+ ).toEqual({ other: './other.js' })+ })++ test('collects targets across multiple subpaths', () => {+ expect(+ packageExportTargetPaths({+ exports: {+ '.': { types: './dist/index.d.ts', import: './dist/index.js' },+ './feature': { import: './dist/feature.js' }+ }+ })+ ).toEqual(['./dist/index.d.ts', './dist/index.js', './dist/feature.js'])+ })++ test('collects nested and wildcard export targets', () => {+ expect(+ packageExportTargetPaths({+ exports: {+ './feature/*': { types: './dist/*.d.ts', import: ['./dist/*.js', null] }+ }+ })+ ).toEqual(['./dist/*.d.ts', './dist/*.js'])+ })+})diff --git a/tools/package-artifacts/tests/workspace-identity.test.ts b/tools/package-artifacts/tests/workspace-identity.test.tsnew file mode 100644index 000000000..099eeface--- /dev/null+++ b/tools/package-artifacts/tests/workspace-identity.test.ts@@ -0,0 +1,71 @@+import { describe, expect, test } from 'bun:test'+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { runCommand } from '../src/process'++describe('workspace module identity', () => {+ test('Bun source exports unify imports across different tsconfig scopes', async () => {+ const root = await mkdtemp(join(tmpdir(), 'workspace-identity-'))+ try {+ await mkdir(join(root, 'packages/graph/src'), { recursive: true })+ await mkdir(join(root, 'packages/graph/dist'), { recursive: true })+ await mkdir(join(root, 'packages/consumer'), { recursive: true })+ await mkdir(join(root, 'node_modules/@fixture'), { recursive: true })+ await symlink('../../packages/graph', join(root, 'node_modules/@fixture/graph'))+ await writeFile(+ join(root, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: { paths: { '@fixture/graph': ['./packages/graph/src/index.ts'] } }+ })+ )+ await writeFile(+ join(root, 'packages/consumer/tsconfig.json'),+ JSON.stringify({+ compilerOptions: { paths: { '#consumer/*': ['./src/*'] } }+ })+ )+ const implementation = 'let next = 0; export class Graph { id = ++next }'+ await writeFile(join(root, 'packages/graph/src/index.ts'), implementation)+ await writeFile(join(root, 'packages/graph/dist/index.js'), implementation)+ await writeFile(+ join(root, 'packages/consumer/index.ts'),+ "export { Graph } from '@fixture/graph'"+ )+ await writeFile(+ join(root, 'check.ts'),+ `+import { Graph as Direct } from '@fixture/graph'+import { Graph as Indirect } from './packages/consumer/index.ts'+console.log(JSON.stringify({ same: Direct === Indirect, ids: [new Direct().id, new Indirect().id] }))+`+ )+ for (const sourceFirst of [false, true]) {+ const conditions: Record<string, string> = {}+ if (sourceFirst) conditions.bun = './src/index.ts'+ conditions.import = './dist/index.js'+ conditions.default = './dist/index.js'+ await writeFile(+ join(root, 'packages/graph/package.json'),+ JSON.stringify({+ name: '@fixture/graph',+ type: 'module',+ exports: { '.': conditions }+ })+ )+ const result = await runCommand({+ command: process.execPath,+ args: ['check.ts'],+ cwd: root,+ timeoutMs: 10_000+ })+ expect(JSON.parse(result.stdout)).toEqual(+ sourceFirst ? { same: true, ids: [1, 2] } : { same: false, ids: [1, 1] }+ )+ }+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })+})diff --git a/tools/package-quality/package.json b/tools/package-quality/package.jsonindex 3fe7d6ecd..58c751828 100644--- a/tools/package-quality/package.json+++ b/tools/package-quality/package.json@@ -2,10 +2,14 @@"name": "@open-pencil/package-quality-tools","private": true,"type": "module",+ "exports": {+ "./consumer": "./src/smoke/consumer.ts"+ },"scripts": {"test": "bun test tests"},"dependencies": {+ "@open-pencil/package-artifacts": "workspace:*","citty": "^0.1.6"}}diff --git a/tools/package-quality/src/checks/attw.ts b/tools/package-quality/src/checks/attw.tsindex 69dbd8fe7..d2d1bf88f 100644--- a/tools/package-quality/src/checks/attw.ts+++ b/tools/package-quality/src/checks/attw.ts@@ -1,26 +1,12 @@import { publicPackageDirs } from '../packages'--let failed = false--for (const packageDir of publicPackageDirs) {- const proc = Bun.spawnSync(- ['bun', 'attw', '--pack', packageDir, '--profile', 'esm-only', '--format', 'ascii'],- {- stdout: 'pipe',- stderr: 'pipe'- }+import { runPackageChecks } from './run'++export async function checkTypes(root: string): Promise<void> {+ await runPackageChecks(+ (await publicPackageDirs(root)).map((packageDir) => ({+ command: 'bun',+ args: ['attw', '--pack', packageDir, '--profile', 'esm-only', '--format', 'ascii'],+ cwd: root+ })))-- const stdout = proc.stdout.toString()- const stderr = proc.stderr.toString()- if (!proc.success) {- console.error(`ATTW failed for ${packageDir}`)- if (stdout) console.error(stdout)- if (stderr) console.error(stderr)- failed = true- }}--if (failed) process.exit(1)--console.log('ATTW package type-resolution checks passed.')diff --git a/tools/package-quality/src/checks/metadata.ts b/tools/package-quality/src/checks/metadata.tsindex f04f73e0a..4b3fcb123 100644--- a/tools/package-quality/src/checks/metadata.ts+++ b/tools/package-quality/src/checks/metadata.ts@@ -1,136 +1,36 @@-import { readFileSync } from 'node:fs'import { join } from 'node:path'-import { publicPackageDirs } from '../packages'--interface PackageJSON {- name: string- version: string- main?: string- types?: string- files?: string[]- bin?: Record<string, string> | string- exports?: unknown- publishConfig?: Record<string, unknown>-}--const errors: string[] = []--function isDeclarationPath(value: string): boolean {- return /\.d\.[cm]?ts$/.test(value)-}--function readPackageJSON(packageDir: string): PackageJSON {- return JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'))-}--const rootPackage = readPackageJSON('.')-const expectedVersion = rootPackage.version--function checkRuntimePath(packageName: string, field: string, value: string): void {- if (value.endsWith('.ts') && !value.endsWith('.d.ts')) {- errors.push(`${packageName}: ${field} must not point to runtime TypeScript (${value})`)- }- if (value.startsWith('./src/')) {- errors.push(`${packageName}: ${field} must not point to source files (${value})`)- }-}--function checkIncludedRuntimePath(- packageName: string,- field: string,- value: string,- files: string[]-): void {- checkRuntimePath(packageName, field, value)- const normalized = value.replace(/^\.\//, '')- if (normalized === 'package.json') return- const topLevelDir = normalized.split('/')[0]- if (topLevelDir && !files.includes(topLevelDir)) {- errors.push(- `${packageName}: ${field} points to ${value}, but files does not include ${topLevelDir}`- )- }-}--function checkIncludedTypePath(- packageName: string,- field: string,- value: string,- files: string[]-): void {- if (!isDeclarationPath(value)) {- errors.push(`${packageName}: ${field} must point to a declaration file (${value})`)- }- if (value.startsWith('./src/')) {- errors.push(`${packageName}: ${field} must not point to source files (${value})`)- }- const normalized = value.replace(/^\.\//, '')- const topLevelDir = normalized.split('/')[0]- if (topLevelDir && !files.includes(topLevelDir)) {- errors.push(- `${packageName}: ${field} points to ${value}, but files does not include ${topLevelDir}`- )- }-}--function walkExports(- packageName: string,- value: unknown,- files: string[],- path: string[] = []-): void {- if (typeof value === 'string') {- const key = path.at(-1)- if (key === 'bun') return- if (key === 'types') {- checkIncludedTypePath(packageName, `exports.${path.join('.')}`, value, files)- } else {- checkIncludedRuntimePath(packageName, `exports.${path.join('.')}`, value, files)- }- return- }- if (!value || typeof value !== 'object') return- for (const [key, child] of Object.entries(value)) {- walkExports(packageName, child, files, [...path, key])- }-}--for (const packageDir of publicPackageDirs) {- const pkg = readPackageJSON(packageDir)-- if (pkg.version !== expectedVersion) {- errors.push(`${pkg.name}: version ${pkg.version} must match root version ${expectedVersion}`)- }-- if (!pkg.files?.includes('dist')) {- errors.push(`${pkg.name}: files must include dist`)- }-- if (pkg.main) checkRuntimePath(pkg.name, 'main', pkg.main)- if (pkg.types) checkIncludedTypePath(pkg.name, 'types', pkg.types, pkg.files ?? [])-- if (typeof pkg.bin === 'string') {- checkIncludedRuntimePath(pkg.name, 'bin', pkg.bin, pkg.files ?? [])- } else if (pkg.bin) {- for (const [name, target] of Object.entries(pkg.bin)) {- checkIncludedRuntimePath(pkg.name, `bin.${name}`, target, pkg.files ?? [])+import {+ discoverPublicPackages,+ readPackageManifest,+ validateManifest,+ type PackageDiagnostic+} from '@open-pencil/package-artifacts'++export async function validatePackageMetadata(root: string): Promise<PackageDiagnostic[]> {+ const packages = await discoverPublicPackages(root)+ if (packages.length === 0) {+ return [+ { field: 'workspaces', message: 'no public packages discovered', packageName: '<root>' }+ ]+ }++ const { version: expectedVersion } = await readPackageManifest(join(root, 'package.json'))+ const diagnostics = packages.flatMap(({ manifest }) => validateManifest(manifest))+ for (const { manifest } of packages) {+ if (manifest.version !== expectedVersion) {+ diagnostics.push({+ packageName: manifest.name,+ field: 'version',+ message: `${manifest.version} must match ${expectedVersion}`+ })}}-- walkExports(pkg.name, pkg.exports, pkg.files ?? [])-- if (- pkg.publishConfig &&- ('exports' in pkg.publishConfig || 'main' in pkg.publishConfig || 'types' in pkg.publishConfig)- ) {- errors.push(`${pkg.name}: publishConfig must not rewrite runtime entrypoints`)- }+ return diagnostics}-if (errors.length > 0) {- console.error(errors.join('\n'))- process.exit(1)+export function formatPackageDiagnostics(diagnostics: PackageDiagnostic[]): string {+ return diagnostics+ .map(({ packageName, field, message }) => `${packageName}: ${field} ${message}`)+ .join('\n')}--console.log('Package metadata is publish-safe.')diff --git a/tools/package-quality/src/checks/publint.ts b/tools/package-quality/src/checks/publint.tsindex 5293cd7ab..97e1acf3c 100644--- a/tools/package-quality/src/checks/publint.ts+++ b/tools/package-quality/src/checks/publint.ts@@ -1,24 +1,12 @@-import { fileURLToPath } from 'node:url'-import { publicPackageDirs } from '../packages'--const rootDir = fileURLToPath(new URL('../../../..', import.meta.url))--for (const packageDir of publicPackageDirs) {- const proc = Bun.spawnSync(['bun', 'publint', packageDir, '--strict'], {- cwd: rootDir,- stdout: 'pipe',- stderr: 'pipe'- })-- const stdout = proc.stdout.toString()- const stderr = proc.stderr.toString()- if (!proc.success) {- console.error(`publint failed for ${packageDir}`)- if (stdout) console.error(stdout)- if (stderr) console.error(stderr)- process.exit(proc.exitCode || 1)- }+import { runPackageChecks } from './run'++export async function checkPublint(root: string): Promise<void> {+ await runPackageChecks(+ (await publicPackageDirs(root)).map((packageDir) => ({+ command: 'bun',+ args: ['publint', packageDir, '--strict'],+ cwd: root+ }))+ )}--console.log('Publint package checks passed.')diff --git a/tools/package-quality/src/checks/run.ts b/tools/package-quality/src/checks/run.tsnew file mode 100644index 000000000..9bfc9a504--- /dev/null+++ b/tools/package-quality/src/checks/run.ts@@ -0,0 +1,25 @@+import { CommandError, runCommand, type CommandRequest } from '@open-pencil/package-artifacts'++/** Finish independent package checks, then report every failure with captured diagnostics. */+export async function runPackageChecks(+ requests: CommandRequest[],+ execute: typeof runCommand = runCommand+): Promise<void> {+ const failures: Error[] = []+ for (const request of requests) {+ try {+ await execute(request)+ } catch (error) {+ if (error instanceof CommandError) {+ failures.push(+ new Error([error.message, error.stdout, error.stderr].filter(Boolean).join('\n'))+ )+ } else {+ failures.push(error instanceof Error ? error : new Error(String(error)))+ }+ }+ }+ if (failures.length > 0) {+ throw new AggregateError(failures, failures.map((error) => error.message).join('\n\n'))+ }+}diff --git a/tools/package-quality/src/commands.ts b/tools/package-quality/src/commands.tsnew file mode 100644index 000000000..8e2297f59--- /dev/null+++ b/tools/package-quality/src/commands.ts@@ -0,0 +1,44 @@+import { defineCommand } from 'citty'++import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts'++import { checkTypes } from './checks/attw'+import { formatPackageDiagnostics, validatePackageMetadata } from './checks/metadata'+import { checkPublint } from './checks/publint'+import { verifyPackedPackages } from './smoke/verify'++const rootArg = { type: 'string', description: 'Explicit workspace root' } as const++async function check(root: string): Promise<void> {+ const diagnostics = await validatePackageMetadata(root)+ if (diagnostics.length > 0) throw new Error(formatPackageDiagnostics(diagnostics))+ await checkPublint(root)+ await checkTypes(root)+ console.log('Package metadata, Publint and ATTW checks passed.')+}++export const checkCommand = defineCommand({+ meta: { name: 'check', description: 'Check public package metadata and declarations' },+ args: { root: rootArg },+ async run({ args }) {+ await check(await resolveWorkspaceRoot(process.cwd(), args.root))+ }+})++export const smokeCommand = defineCommand({+ meta: { name: 'smoke', description: 'Smoke-test built public packages' },+ args: { root: rootArg },+ async run({ args }) {+ await verifyPackedPackages(await resolveWorkspaceRoot(process.cwd(), args.root))+ }+})++export const verifyCommand = defineCommand({+ meta: { name: 'verify', description: 'Run package checks and built-package smoke tests' },+ args: { root: rootArg },+ async run({ args }) {+ const root = await resolveWorkspaceRoot(process.cwd(), args.root)+ await check(root)+ await verifyPackedPackages(root)+ }+})diff --git a/tools/package-quality/src/commands/index.ts b/tools/package-quality/src/commands/index.tsdeleted file mode 100644index 3e3080b8c..000000000--- a/tools/package-quality/src/commands/index.ts+++ /dev/null@@ -1,33 +0,0 @@-import { defineCommand } from 'citty'--import { runPackageQualityCommand } from './run'--export const PACKAGE_CHECK_ENTRYPOINTS = [- 'tools/package-quality/src/checks/metadata.ts',- 'tools/package-quality/src/checks/publint.ts',- 'tools/package-quality/src/checks/attw.ts'-]--export const checkCommand = defineCommand({- meta: { name: 'check', description: 'Check public package metadata and declarations' },- async run() {- await runPackageQualityCommand(PACKAGE_CHECK_ENTRYPOINTS)- }-})--export const smokeCommand = defineCommand({- meta: { name: 'smoke', description: 'Smoke-test built public packages' },- async run() {- await runPackageQualityCommand(['tools/package-quality/src/smoke.ts'])- }-})--export const verifyCommand = defineCommand({- meta: { name: 'verify', description: 'Run package checks and built-package smoke tests' },- async run() {- await runPackageQualityCommand([- ...PACKAGE_CHECK_ENTRYPOINTS,- 'tools/package-quality/src/smoke.ts'- ])- }-})diff --git a/tools/package-quality/src/commands/run.ts b/tools/package-quality/src/commands/run.tsdeleted file mode 100644index 29b99edc6..000000000--- a/tools/package-quality/src/commands/run.ts+++ /dev/null@@ -1,11 +0,0 @@-export async function runPackageQualityCommand(entrypoints: string[]): Promise<void> {- for (const entrypoint of entrypoints) {- const process = Bun.spawn(['bun', entrypoint], {- stdin: 'inherit',- stdout: 'inherit',- stderr: 'inherit'- })- const exitCode = await process.exited- if (exitCode !== 0) throw new Error(`${entrypoint} exited with code ${exitCode}`)- }-}diff --git a/tools/package-quality/src/packages.ts b/tools/package-quality/src/packages.tsindex 4c687345a..bb5833756 100644--- a/tools/package-quality/src/packages.ts+++ b/tools/package-quality/src/packages.ts@@ -1,26 +1,5 @@-import { readFileSync } from 'node:fs'-import { join } from 'node:path'-import { fileURLToPath } from 'node:url'+import { discoverPublicPackages } from '@open-pencil/package-artifacts'-interface RootPackageJSON {- workspaces?: string[]+export async function publicPackageDirs(root: string): Promise<string[]> {+ return (await discoverPublicPackages(root)).map(({ directory }) => directory)}--interface WorkspacePackageJSON {- private?: boolean-}--const rootDir = fileURLToPath(new URL('../../..', import.meta.url))--function readJSON<T>(path: string): T {- return JSON.parse(readFileSync(path, 'utf8')) as T-}--const rootPackage = readJSON<RootPackageJSON>(join(rootDir, 'package.json'))--export const publicPackageDirs = (rootPackage.workspaces ?? []).filter((workspaceDir) => {- const workspacePackage = readJSON<WorkspacePackageJSON>(- join(rootDir, workspaceDir, 'package.json')- )- return workspacePackage.private !== true-})diff --git a/tools/package-quality/src/smoke.ts b/tools/package-quality/src/smoke.tsdeleted file mode 100644index 41deb5ae1..000000000--- a/tools/package-quality/src/smoke.ts+++ /dev/null@@ -1,287 +0,0 @@-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { basename, join } from 'node:path'-import { fileURLToPath } from 'node:url'--import { publicPackageDirs } from './packages'--const rootDir = fileURLToPath(new URL('../../..', import.meta.url))-const tsgoBin = join(- rootDir,- 'node_modules',- '.bin',- process.platform === 'win32' ? 'tsgo.cmd' : 'tsgo'-)--function run(command: string[], cwd = rootDir): string {- const proc = Bun.spawnSync(command, { cwd, stdout: 'pipe', stderr: 'pipe' })- const stdout = proc.stdout.toString()- const stderr = proc.stderr.toString()- if (!proc.success) {- console.error(`$ ${command.join(' ')}`)- if (stdout) console.error(stdout)- if (stderr) console.error(stderr)- process.exit(proc.exitCode || 1)- }- return stdout.trim()-}--const EVAL_TIMEOUT_S = 30--function nodeEval(code: string, cwd: string): void {- const args =- process.platform === 'win32'- ? ['node', '--input-type=module', '--eval', code]- : ['timeout', String(EVAL_TIMEOUT_S), 'node', '--input-type=module', '--eval', code]- run(args, cwd)-}--function writeTypeConsumer(cwd: string): void {- writeFileSync(- join(cwd, 'tsconfig.package-smoke.json'),- JSON.stringify(- {- compilerOptions: {- strict: true,- target: 'ES2022',- module: 'NodeNext',- moduleResolution: 'NodeNext',- lib: ['ES2022', 'DOM'],- typeRoots: [join(rootDir, 'node_modules', '@types')],- skipLibCheck: true,- noEmit: true- },- include: ['package-type-consumer.ts']- },- null,- 2- ),- 'utf8'- )-- writeFileSync(- join(cwd, 'package-type-consumer.ts'),- `import { createEditor, type Editor } from '@open-pencil/core'-import { htmlToDesignDocument, type DesignDocument } from '@open-pencil/dom-css'-import { FIG_PACKAGE_STATUS, type FigContainerDocument } from '@open-pencil/fig'-import { FIG_KIWI_DEFAULT_VERSION, buildFigKiwi } from '@open-pencil/kiwi/fig/container'-import { type GUID as KiwiGUID } from '@open-pencil/kiwi/fig'-import { parsePenFile, type PenDocument } from '@open-pencil/pen'-import { SceneGraph, type Color, type SceneNode, type Vector } from '@open-pencil/scene-graph'-import { testIdSelector } from '@open-pencil/vue'--const graph = new SceneGraph()-const editorFactory: typeof createEditor = createEditor-declare const editor: Editor-declare const designDocument: DesignDocument--const color: Color = { r: 1, g: 0.5, b: 0, a: 1 }-const vector: Vector = { x: 1, y: 2 }-const maybeNode: SceneNode | undefined = graph.getPages()[0]-const penDocument: PenDocument = { version: '1', children: [] }-const figDocument: FigContainerDocument = {- schemaDeflated: new Uint8Array([1]),- dataRaw: new Uint8Array([2])-}-const kiwiGuid: KiwiGUID = { sessionID: 1, localID: 2 }--void editorFactory-void editor-void designDocument-void color-void vector-void maybeNode-void penDocument-void figDocument-void kiwiGuid-void FIG_PACKAGE_STATUS-void FIG_KIWI_DEFAULT_VERSION-void buildFigKiwi-void parsePenFile-void htmlToDesignDocument-void testIdSelector-`,- 'utf8'- )-}--function checkTypeConsumer(cwd: string): void {- writeTypeConsumer(cwd)- run([tsgoBin, '--noEmit', '-p', 'tsconfig.package-smoke.json'], cwd)-}--interface PackageJSON {- name: string- types?: string- exports?: unknown-}--function isRecord(value: unknown): value is Record<string, unknown> {- return Boolean(value) && typeof value === 'object' && !Array.isArray(value)-}--function readPackageJSON(packageDir: string): PackageJSON {- return JSON.parse(readFileSync(join(rootDir, packageDir, 'package.json'), 'utf8'))-}--function collectExportTypePaths(value: unknown, paths: string[] = []): string[] {- if (typeof value === 'string') return paths- if (!value || typeof value !== 'object') return paths- for (const [key, child] of Object.entries(value)) {- if (key === 'types' && typeof child === 'string') paths.push(child)- else collectExportTypePaths(child, paths)- }- return paths-}--function packageArchivePath(path: string): string {- return `package/${path.replace(/^\.\//, '')}`-}--function exportKeyToSpecifier(packageName: string, exportKey: string): string | null {- if (exportKey === './package.json') return null- if (exportKey === '.') return packageName- if (!exportKey.startsWith('./')) {- throw new Error(`${packageName}: unsupported export key ${exportKey}`)- }- if (exportKey.includes('*')) {- throw new Error(- `${packageName}: package smoke cannot exhaustively import pattern export ${exportKey}`- )- }- return `${packageName}/${exportKey.slice(2)}`-}--function collectPublicImportSpecifiers(packageJSON: PackageJSON): string[] {- const { exports } = packageJSON- if (!exports) return []- if (typeof exports === 'string') return [packageJSON.name]- if (!isRecord(exports)) return []-- const keys = Object.keys(exports)- if (keys.length === 0) return []-- const hasExportMapKeys = keys.some((key) => key.startsWith('.'))- if (!hasExportMapKeys) return [packageJSON.name]-- const specifiers: string[] = []- for (const key of keys) {- const specifier = exportKeyToSpecifier(packageJSON.name, key)- if (specifier) specifiers.push(specifier)- }- return specifiers-}--const tempDir = mkdtempSync(join(tmpdir(), 'open-pencil-package-smoke-'))--try {- run(['bun', 'run', 'build:packages'])-- const tarballs: string[] = []- const publicImportSpecifiers = new Set<string>()- for (const packageDir of publicPackageDirs) {- const packageJSON = readPackageJSON(packageDir)- for (const specifier of collectPublicImportSpecifiers(packageJSON)) {- publicImportSpecifiers.add(specifier)- }- const output = run(- ['bun', 'pm', 'pack', '--destination', tempDir, '--quiet'],- join(rootDir, packageDir)- )- const filename = output- .split('\n')- .map((line) => line.trim())- .findLast((line) => line.length > 0)- if (!filename) throw new Error(`No tarball produced for ${packageDir}`)- const tarball = filename.startsWith('/') ? filename : join(tempDir, filename)- tarballs.push(tarball)-- const contents = run(['tar', '-tf', tarball])- const runtimeTs = contents- .split('\n')- .filter((entry) => /package\/src\/.*\.ts$/.test(entry) && !entry.endsWith('.d.ts'))- if (runtimeTs.length > 0) {- console.error(`${basename(tarball)} includes runtime TypeScript:\n${runtimeTs.join('\n')}`)- process.exit(1)- }-- const entries = new Set(contents.split('\n'))- const typePaths = [- ...(packageJSON.types ? [packageJSON.types] : []),- ...collectExportTypePaths(packageJSON.exports)- ]- const missingTypePaths = typePaths- .map(packageArchivePath)- .filter((entry) => !entries.has(entry))- if (missingTypePaths.length > 0) {- console.error(- `${basename(tarball)} is missing declared type files:\n${missingTypePaths.join('\n')}`- )- process.exit(1)- }- }-- run(['npm', 'init', '-y'], tempDir)- run(['npm', 'install', '--ignore-scripts', '--no-audit', '--no-fund', ...tarballs], tempDir)-- // @open-pencil/mcp/stdio is a CLI entry point that creates a WebSocket- // connection on import. It is verified via the openpencil-mcp --help- // command below, not via import eval.- const evalSkipSpecifiers = new Set(['@open-pencil/mcp/stdio'])-- for (const specifier of [...publicImportSpecifiers].sort()) {- if (evalSkipSpecifiers.has(specifier)) continue- nodeEval(`await import(${JSON.stringify(specifier)})`, tempDir)- }-- checkTypeConsumer(tempDir)-- nodeEval(- "const { guidToString } = await import('@open-pencil/kiwi/fig/guid'); if (guidToString({ sessionID: 1, localID: 2 }) !== '1:2') throw new Error('Kiwi GUID subpath failed')",- tempDir- )- nodeEval(- "const { buildFigKiwi, parseFigKiwiChunks } = await import('@open-pencil/kiwi/fig/container'); const chunks = parseFigKiwiChunks(buildFigKiwi(new Uint8Array([1]), new Uint8Array([2]))); if (chunks?.length !== 2) throw new Error('Kiwi container subpath failed')",- tempDir- )- nodeEval(- "const { FIG_PACKAGE_STATUS, effectiveFigmaRawNodeFields, parseFigBuffer, writeFigArchive, readFigContainer, writeFigContainer } = await import('@open-pencil/fig'); if (FIG_PACKAGE_STATUS !== 'archive-api' || typeof effectiveFigmaRawNodeFields !== 'function' || typeof parseFigBuffer !== 'function' || typeof writeFigArchive !== 'function') throw new Error('Fig package status smoke failed'); const document = readFigContainer(writeFigContainer({ schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) })); if (document.dataRaw[0] !== 2) throw new Error('Fig container smoke failed')",- tempDir- )- nodeEval(- "const { convertLineHeight, sceneNodeToKiwi } = await import('@open-pencil/fig/node-change'); if (convertLineHeight({ value: 120, units: 'PERCENT' }, 20) !== 24 || typeof sceneNodeToKiwi !== 'function') throw new Error('Fig NodeChange subpath failed')",- tempDir- )- nodeEval(- "const { populateAndApplyOverrides } = await import('@open-pencil/fig/instance-overrides'); if (typeof populateAndApplyOverrides !== 'function') throw new Error('Fig instance override subpath failed')",- tempDir- )- nodeEval(- "const { SceneGraph } = await import('@open-pencil/scene-graph'); const graph = new SceneGraph(); if (graph.getPages().length !== 1) throw new Error('SceneGraph package smoke failed')",- tempDir- )- nodeEval(- "const { parsePenFile } = await import('@open-pencil/pen'); const graph = parsePenFile(JSON.stringify({ version: '1', children: [{ id: 'frame', type: 'frame', width: 100, height: 50 }] })); if (graph.getPages()[0].childIds.length !== 1) throw new Error('Pen package smoke failed')",- tempDir- )- nodeEval(- "const { htmlToSceneGraph } = await import('@open-pencil/dom-css'); const graph = await htmlToSceneGraph('<div class=card>OpenPencil</div>', { cssText: '.card { width: 320px; }' }); if (graph.getPages()[0].width !== 320) throw new Error('DOM/CSS scene graph smoke failed')",- tempDir- )- nodeEval(- "const browser = await import('@open-pencil/dom-css/browser'); for (const key of ['browserHTMLToDesignDocument', 'browserHTMLToSceneGraph', 'browserTailwindJSXToSceneGraph']) if (typeof browser[key] !== 'function') throw new Error('DOM/CSS browser export missing: ' + key)",- tempDir- )- nodeEval(- "const { jsx, jsxToDesignDocument } = await import('@open-pencil/dom-css/jsx-runtime'); const document = await jsxToDesignDocument(jsx('section', { class: 'card', style: { width: '120px' }, children: 'OpenPencil' })); const node = document.children[0]; if (node?.type !== 'element' || node.inlineStyle?.width !== '120px') throw new Error('DOM/CSS JSX runtime smoke failed')",- tempDir- )-- run(['node', 'node_modules/.bin/openpencil', '--help'], tempDir)- run(['node', 'node_modules/.bin/openpencil-mcp', '--help'], tempDir)- run(['node', 'node_modules/.bin/openpencil-mcp-http', '--help'], tempDir)-- console.log('Packed package smoke tests passed.')-} finally {- rmSync(tempDir, { recursive: true, force: true })-}diff --git a/tools/package-quality/src/smoke/consumer.ts b/tools/package-quality/src/smoke/consumer.tsnew file mode 100644index 000000000..4a1c3d1d9--- /dev/null+++ b/tools/package-quality/src/smoke/consumer.ts@@ -0,0 +1,37 @@+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { inspectTarball } from '@open-pencil/package-artifacts/tarball'++import { installPackedPackages } from './install'+import { verifyPackageBinaries, verifyPublicImports, verifyRuntimeScenarios } from './runtime'+import { runtimeScenarios } from './scenarios'+import { verifyTypeConsumer } from './type-consumer'++/** Verify an entire OpenPencil artifact set, without rebuilding or modifying its archives. */+export async function verifyArtifactConsumers(root: string, tarballs: string[]): Promise<void> {+ if (tarballs.length === 0) throw new Error('Cannot verify an empty artifact set')+ const inspections = await Promise.all(tarballs.map(inspectTarball))+ const diagnostics = inspections.flatMap(({ diagnostics }) => diagnostics)+ if (diagnostics.length > 0) {+ throw new Error(+ diagnostics+ .map(({ packageName, field, message }) => `${packageName}: ${field} ${message}`)+ .join('\n')+ )+ }+ const consumer = await mkdtemp(join(tmpdir(), 'open-pencil-artifact-consumer-'))+ try {+ await installPackedPackages(consumer, tarballs)+ await verifyPublicImports(+ inspections.map(({ manifest }) => manifest),+ consumer+ )+ await verifyRuntimeScenarios(runtimeScenarios, consumer)+ await verifyTypeConsumer(root, consumer)+ await verifyPackageBinaries(consumer)+ } finally {+ await rm(consumer, { recursive: true, force: true })+ }+}diff --git a/tools/package-quality/src/smoke/install.ts b/tools/package-quality/src/smoke/install.tsnew file mode 100644index 000000000..03d9a38b2--- /dev/null+++ b/tools/package-quality/src/smoke/install.ts@@ -0,0 +1,17 @@+import { mkdir } from 'node:fs/promises'++import { runCommand } from '@open-pencil/package-artifacts'++export async function installPackedPackages(+ consumerDirectory: string,+ tarballs: string[]+): Promise<void> {+ await mkdir(consumerDirectory, { recursive: true })+ await runCommand({ command: 'npm', args: ['init', '-y'], cwd: consumerDirectory })+ await runCommand({+ command: 'npm',+ args: ['install', '--ignore-scripts', '--no-audit', '--no-fund', ...tarballs],+ cwd: consumerDirectory,+ timeoutMs: 120_000+ })+}diff --git a/tools/package-quality/src/smoke/pack.ts b/tools/package-quality/src/smoke/pack.tsnew file mode 100644index 000000000..aed929a1e--- /dev/null+++ b/tools/package-quality/src/smoke/pack.ts@@ -0,0 +1,62 @@+import { mkdir } from 'node:fs/promises'+import { isAbsolute, join } from 'node:path'++import { parseNpmPack, runCommand, type WorkspacePackage } from '@open-pencil/package-artifacts'+import { inspectTarball, type TarballInspection } from '@open-pencil/package-artifacts/tarball'++export interface PackedPackageSet {+ inspections: TarballInspection[]+ packages: WorkspacePackage[]+ tarballs: string[]+}++function tarballFromOutput(output: string, directory: string): string {+ const filename = output+ .split('\n')+ .map((line: string) => line.trim())+ .reverse()+ .find((line: string) => line.endsWith('.tgz'))+ if (!filename) throw new Error(`Package manager did not report a tarball in ${directory}`)+ return isAbsolute(filename) ? filename : join(directory, filename)+}++export async function packPublicPackages(+ root: string,+ outputDirectory: string,+ packages: WorkspacePackage[],+ packageManager: 'bun' | 'npm'+): Promise<PackedPackageSet> {+ await mkdir(outputDirectory, { recursive: true })+ const tarballs: string[] = []+ for (const pkg of packages) {+ const command =+ packageManager === 'bun'+ ? ['bun', 'pm', 'pack', '--ignore-scripts', '--destination', outputDirectory, '--quiet']+ : ['npm', 'pack', '--json', '--ignore-scripts', '--pack-destination', outputDirectory]+ const result = await runCommand({+ command: command[0] ?? packageManager,+ args: command.slice(1),+ cwd: join(root, pkg.directory),+ timeoutMs: 60_000+ })+ const tarball =+ packageManager === 'bun'+ ? tarballFromOutput(result.stdout, outputDirectory)+ : npmTarballFromOutput(result.stdout, outputDirectory)+ tarballs.push(tarball)+ }+ const inspections = await Promise.all(tarballs.map(inspectTarball))+ const diagnostics = inspections.flatMap(({ diagnostics }) => diagnostics)+ if (diagnostics.length > 0) {+ throw new Error(+ diagnostics+ .map(({ packageName, field, message }) => `${packageName}: ${field} ${message}`)+ .join('\n')+ )+ }+ return { inspections, packages, tarballs }+}++function npmTarballFromOutput(output: string, directory: string): string {+ return join(directory, parseNpmPack(output).filename)+}diff --git a/tools/package-quality/src/smoke/runtime.ts b/tools/package-quality/src/smoke/runtime.tsnew file mode 100644index 000000000..406b07e8a--- /dev/null+++ b/tools/package-quality/src/smoke/runtime.ts@@ -0,0 +1,75 @@+import { join } from 'node:path'++import {+ concreteImportSpecifiers,+ runCommand,+ type PackageManifest+} from '@open-pencil/package-artifacts'++export type RuntimeName = 'bun' | 'node'++const RUNTIME_TIMEOUT_MS = 30_000++function runtimeEvalArgs(runtime: RuntimeName, code: string): string[] {+ return runtime === 'node' ? ['--input-type=module', '--eval', code] : ['--eval', code]+}++export async function evaluateRuntime(+ runtime: RuntimeName,+ code: string,+ consumerDirectory: string+): Promise<void> {+ await runCommand({+ command: runtime,+ args: runtimeEvalArgs(runtime, code),+ cwd: consumerDirectory,+ timeoutMs: RUNTIME_TIMEOUT_MS+ })+}++export async function verifyPublicImports(+ manifests: PackageManifest[],+ consumerDirectory: string+): Promise<void> {+ const skipped = new Set(['@open-pencil/mcp/stdio'])+ const specifiers = manifests+ .flatMap(concreteImportSpecifiers)+ .filter((specifier) => !skipped.has(specifier))+ .sort()++ for (const runtime of ['node', 'bun'] as const) {+ for (const specifier of specifiers) {+ await evaluateRuntime(+ runtime,+ `await import(${JSON.stringify(specifier)})`,+ consumerDirectory+ )+ }+ }+}++export async function verifyRuntimeScenarios(+ scenarios: ReadonlyArray<{ code: string }>,+ consumerDirectory: string+): Promise<void> {+ for (const runtime of ['node', 'bun'] as const) {+ for (const scenario of scenarios) {+ await evaluateRuntime(runtime, scenario.code, consumerDirectory)+ }+ }+}++export async function verifyPackageBinaries(consumerDirectory: string): Promise<void> {+ const binaryDirectory = join(consumerDirectory, 'node_modules', '.bin')+ const binaries = ['openpencil', 'openpencil-mcp', 'openpencil-mcp-http']+ for (const runtime of ['node', 'bun'] as const) {+ for (const binary of binaries) {+ await runCommand({+ command: runtime,+ args: [join(binaryDirectory, binary), '--help'],+ cwd: consumerDirectory,+ timeoutMs: RUNTIME_TIMEOUT_MS+ })+ }+ }+}diff --git a/tools/package-quality/src/smoke/scenarios.ts b/tools/package-quality/src/smoke/scenarios.tsnew file mode 100644index 000000000..780cba33f--- /dev/null+++ b/tools/package-quality/src/smoke/scenarios.ts@@ -0,0 +1,47 @@+export interface RuntimeScenario {+ code: string+ name: string+}++export const runtimeScenarios: RuntimeScenario[] = [+ {+ name: 'Kiwi GUID subpath',+ code: "const { guidToString } = await import('@open-pencil/kiwi/fig/guid'); if (guidToString({ sessionID: 1, localID: 2 }) !== '1:2') throw new Error('Kiwi GUID subpath failed')"+ },+ {+ name: 'Kiwi container subpath',+ code: "const { buildFigKiwi, parseFigKiwiChunks } = await import('@open-pencil/kiwi/fig/container'); const chunks = parseFigKiwiChunks(buildFigKiwi(new Uint8Array([1]), new Uint8Array([2]))); if (chunks?.length !== 2) throw new Error('Kiwi container subpath failed')"+ },+ {+ name: 'FIG archive API',+ code: "const { FIG_PACKAGE_STATUS, effectiveFigmaRawNodeFields, parseFigBuffer, writeFigArchive, readFigContainer, writeFigContainer } = await import('@open-pencil/fig'); if (FIG_PACKAGE_STATUS !== 'archive-api' || typeof effectiveFigmaRawNodeFields !== 'function' || typeof parseFigBuffer !== 'function' || typeof writeFigArchive !== 'function') throw new Error('Fig package status smoke failed'); const document = readFigContainer(writeFigContainer({ schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) })); if (document.dataRaw[0] !== 2) throw new Error('Fig container smoke failed')"+ },+ {+ name: 'FIG NodeChange API',+ code: "const { convertLineHeight, sceneNodeToKiwi } = await import('@open-pencil/fig/node-change'); if (convertLineHeight({ value: 120, units: 'PERCENT' }, 20) !== 24 || typeof sceneNodeToKiwi !== 'function') throw new Error('Fig NodeChange subpath failed')"+ },+ {+ name: 'FIG instance override API',+ code: "const { populateAndApplyOverrides } = await import('@open-pencil/fig/instance-overrides'); if (typeof populateAndApplyOverrides !== 'function') throw new Error('Fig instance override subpath failed')"+ },+ {+ name: 'SceneGraph package',+ code: "const { SceneGraph } = await import('@open-pencil/scene-graph'); const graph = new SceneGraph(); if (graph.getPages().length !== 1) throw new Error('SceneGraph package smoke failed')"+ },+ {+ name: 'PEN parser',+ code: "const { parsePenFile } = await import('@open-pencil/pen'); const graph = parsePenFile(JSON.stringify({ version: '1', children: [{ id: 'frame', type: 'frame', width: 100, height: 50 }] })); if (graph.getPages()[0].childIds.length !== 1) throw new Error('Pen package smoke failed')"+ },+ {+ name: 'DOM/CSS conversion',+ code: "const { htmlToSceneGraph } = await import('@open-pencil/dom-css'); const graph = await htmlToSceneGraph('<div class=card>OpenPencil</div>', { cssText: '.card { width: 320px; }' }); if (graph.getPages()[0].width !== 320) throw new Error('DOM/CSS scene graph failed')"+ },+ {+ name: 'DOM/CSS browser API',+ code: "const browser = await import('@open-pencil/dom-css/browser'); for (const key of ['browserHTMLToDesignDocument', 'browserHTMLToSceneGraph', 'browserTailwindJSXToSceneGraph']) if (typeof browser[key] !== 'function') throw new Error('DOM/CSS browser export missing: ' + key)"+ },+ {+ name: 'DOM/CSS JSX runtime',+ code: "const { jsx, jsxToDesignDocument } = await import('@open-pencil/dom-css/jsx-runtime'); const document = await jsxToDesignDocument(jsx('section', { class: 'card', style: { width: '120px' }, children: 'OpenPencil' })); const node = document.children[0]; if (node?.type !== 'element' || node.inlineStyle?.width !== '120px') throw new Error('DOM/CSS JSX runtime failed')"+ }+]diff --git a/tools/package-quality/src/smoke/type-consumer.ts b/tools/package-quality/src/smoke/type-consumer.tsnew file mode 100644index 000000000..7b8a8ecbe--- /dev/null+++ b/tools/package-quality/src/smoke/type-consumer.ts@@ -0,0 +1,65 @@+import { writeFile } from 'node:fs/promises'+import { join } from 'node:path'++import { runCommand } from '@open-pencil/package-artifacts'++const TYPE_CONSUMER = `import { createEditor, type Editor } from '@open-pencil/core'+import { htmlToDesignDocument, type DesignDocument } from '@open-pencil/dom-css'+import { FIG_PACKAGE_STATUS, type FigContainerDocument } from '@open-pencil/fig'+import { FIG_KIWI_DEFAULT_VERSION, buildFigKiwi } from '@open-pencil/kiwi/fig/container'+import { type GUID as KiwiGUID } from '@open-pencil/kiwi/fig'+import { parsePenFile, type PenDocument } from '@open-pencil/pen'+import { SceneGraph, type Color, type SceneNode, type Vector } from '@open-pencil/scene-graph'+import { testIdSelector } from '@open-pencil/vue'++const graph = new SceneGraph()+const editorFactory: typeof createEditor = createEditor+declare const editor: Editor+declare const designDocument: DesignDocument+const color: Color = { r: 1, g: 0.5, b: 0, a: 1 }+const vector: Vector = { x: 1, y: 2 }+const maybeNode: SceneNode | undefined = graph.getPages()[0]+const penDocument: PenDocument = { version: '1', children: [] }+const figDocument: FigContainerDocument = { schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) }+const kiwiGuid: KiwiGUID = { sessionID: 1, localID: 2 }+void editorFactory; void editor; void designDocument; void color; void vector; void maybeNode+void penDocument; void figDocument; void kiwiGuid; void FIG_PACKAGE_STATUS+void FIG_KIWI_DEFAULT_VERSION; void buildFigKiwi; void parsePenFile; void htmlToDesignDocument+void testIdSelector+`++export async function verifyTypeConsumer(root: string, consumerDirectory: string): Promise<void> {+ await writeFile(+ join(consumerDirectory, 'tsconfig.package-smoke.json'),+ `${JSON.stringify(+ {+ compilerOptions: {+ strict: true,+ target: 'ES2022',+ module: 'NodeNext',+ moduleResolution: 'NodeNext',+ lib: ['ES2022', 'DOM'],+ typeRoots: [join(root, 'node_modules', '@types')],+ skipLibCheck: true,+ noEmit: true+ },+ include: ['package-type-consumer.ts']+ },+ null,+ 2+ )}\n`+ )+ await writeFile(join(consumerDirectory, 'package-type-consumer.ts'), TYPE_CONSUMER)+ const executable = join(+ root,+ 'node_modules',+ '.bin',+ process.platform === 'win32' ? 'tsgo.cmd' : 'tsgo'+ )+ await runCommand({+ command: executable,+ args: ['--noEmit', '-p', 'tsconfig.package-smoke.json'],+ cwd: consumerDirectory,+ timeoutMs: 30_000+ })+}diff --git a/tools/package-quality/src/smoke/verify.ts b/tools/package-quality/src/smoke/verify.tsnew file mode 100644index 000000000..d4eea9f22--- /dev/null+++ b/tools/package-quality/src/smoke/verify.ts@@ -0,0 +1,27 @@+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { discoverPublicPackages, orderPackagesByDependencies } from '@open-pencil/package-artifacts'++import { verifyArtifactConsumers } from './consumer'+import { packPublicPackages } from './pack'++export async function verifyPackedPackages(root: string): Promise<void> {+ const temporaryRoot = await mkdtemp(join(tmpdir(), 'open-pencil-package-smoke-'))+ try {+ const packages = orderPackagesByDependencies(await discoverPublicPackages(root))+ // Raw npm packing retains workspace:* dependencies. Inspect it without claiming+ // installation compatibility; Bun packing normalizes those dependencies.+ await packPublicPackages(root, join(temporaryRoot, 'npm-tarballs'), packages, 'npm')+ const packageSet = await packPublicPackages(+ root,+ join(temporaryRoot, 'bun-tarballs'),+ packages,+ 'bun'+ )+ await verifyArtifactConsumers(root, packageSet.tarballs)+ } finally {+ await rm(temporaryRoot, { recursive: true, force: true })+ }+}diff --git a/tools/package-quality/tests/checks.test.ts b/tools/package-quality/tests/checks.test.tsnew file mode 100644index 000000000..95dd32d0d--- /dev/null+++ b/tools/package-quality/tests/checks.test.ts@@ -0,0 +1,30 @@+import { expect, test } from 'bun:test'++import { CommandError, type CommandRequest } from '@open-pencil/package-artifacts'++import { runPackageChecks } from '../src/checks/run'++test('package checks finish all requests and retain output from every failure', async () => {+ const visited: string[] = []+ const requests = ['first', 'second', 'third'].map((command) => ({ command, cwd: '/fixture' }))+ const error = await runPackageChecks(requests, async (request: CommandRequest) => {+ visited.push(request.command)+ if (request.command !== 'second') {+ throw new CommandError(+ `failed ${request.command}`,+ request,+ 1,+ `stdout ${request.command}`,+ `stderr ${request.command}`,+ false+ )+ }+ return { stdout: '', stderr: '' }+ }).catch((caught: unknown) => caught)+ expect(visited).toEqual(['first', 'second', 'third'])+ expect(error).toBeInstanceOf(AggregateError)+ if (!(error instanceof AggregateError)) throw new Error('Expected aggregate diagnostics')+ expect(error.errors).toHaveLength(2)+ expect(error.message).toContain('stdout first')+ expect(error.message).toContain('stderr third')+})diff --git a/tools/package-quality/tests/packed-resolution.test.ts b/tools/package-quality/tests/packed-resolution.test.tsnew file mode 100644index 000000000..2788ca232--- /dev/null+++ b/tools/package-quality/tests/packed-resolution.test.ts@@ -0,0 +1,130 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { runCommand } from '@open-pencil/package-artifacts'+import { inspectTarball } from '@open-pencil/package-artifacts/tarball'++async function createPackageFixture(+ root: string,+ bunTarget: string,+ files = ['dist']+): Promise<string> {+ const packageDirectory = join(root, 'package')+ await mkdir(join(packageDirectory, 'dist'), { recursive: true })+ await mkdir(join(packageDirectory, 'src'), { recursive: true })+ await writeFile(join(packageDirectory, 'dist/index.js'), 'export const ready = true\n')+ await writeFile(join(packageDirectory, 'dist/index.d.ts'), 'export declare const ready: true\n')+ await writeFile(+ join(packageDirectory, 'src/index.ts'),+ "export { ready } from '#fixture/value'\n"+ )+ await writeFile(join(packageDirectory, 'src/value.ts'), 'export const ready = true\n')+ await writeFile(+ join(packageDirectory, 'package.json'),+ `${JSON.stringify(+ {+ name: '@fixture/resolution',+ version: '1.0.0',+ type: 'module',+ imports: { '#fixture/*': './src/*.ts' },+ files,+ exports: {+ '.': {+ types: './dist/index.d.ts',+ bun: bunTarget,+ import: './dist/index.js',+ default: './dist/index.js'+ }+ }+ },+ null,+ 2+ )}\n`+ )+ return packageDirectory+}++import { evaluateRuntime } from '../src/smoke/runtime'++const temporaryDirectories: string[] = []++afterEach(async () => {+ await Promise.all(+ temporaryDirectories.splice(0).map((path) => rm(path, { recursive: true, force: true }))+ )+})++async function packAndInstall(bunTarget: string, files = ['dist']) {+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-package-resolution-'))+ temporaryDirectories.push(root)+ const packageDirectory = await createPackageFixture(root, bunTarget, files)+ const artifacts = join(root, 'artifacts')+ const consumer = join(root, 'consumer')+ await mkdir(artifacts)+ await mkdir(consumer)+ const packed = await runCommand({+ command: 'npm',+ args: ['pack', '--json', '--pack-destination', artifacts],+ cwd: packageDirectory+ })+ const filename = (JSON.parse(packed.stdout) as Array<{ filename: string }>)[0]?.filename+ if (!filename) throw new Error('Fixture pack did not produce a tarball')+ const tarball = join(artifacts, filename)+ await runCommand({ command: 'npm', args: ['init', '-y'], cwd: consumer })+ await runCommand({+ command: 'npm',+ args: ['install', '--ignore-scripts', '--no-audit', '--no-fund', tarball],+ cwd: consumer+ })+ return { consumer, tarball }+}++describe('packed runtime resolution', () => {+ test('imports the same packed artifact under Node and Bun', async () => {+ const { consumer, tarball } = await packAndInstall('./dist/index.js')+ expect((await inspectTarball(tarball)).diagnostics).toEqual([])+ for (const runtime of ['node', 'bun'] as const) {+ await evaluateRuntime(+ runtime,+ "const value = await import('@fixture/resolution'); if (!value.ready) throw new Error('not ready')",+ consumer+ )+ }+ })++ test('ships transitive source imports with the source directory', async () => {+ const { consumer, tarball } = await packAndInstall('./src/index.ts', ['dist', 'src'])+ expect((await inspectTarball(tarball)).diagnostics).toEqual([])+ for (const runtime of ['node', 'bun'] as const) {+ await evaluateRuntime(+ runtime,+ "const { ready } = await import('@fixture/resolution'); if (!ready) throw new Error('missing value')",+ consumer+ )+ }+ }, 120_000)++ test('an entrypoint-only file list does not satisfy transitive imports', async () => {+ const { consumer, tarball } = await packAndInstall('./src/index.ts', ['dist', 'src/index.ts'])+ expect((await inspectTarball(tarball)).diagnostics).toEqual([])+ await expect(+ evaluateRuntime('bun', "await import('@fixture/resolution')", consumer)+ ).rejects.toThrow()+ }, 120_000)++ test('detects the source-only Bun condition from issue 663', async () => {+ const { consumer, tarball } = await packAndInstall('./src/index.ts')+ expect((await inspectTarball(tarball)).diagnostics).toEqual([+ expect.objectContaining({+ field: 'exports["."].bun',+ message: 'target is missing (./src/index.ts)'+ })+ ])+ await evaluateRuntime('node', "await import('@fixture/resolution')", consumer)+ await expect(+ evaluateRuntime('bun', "await import('@fixture/resolution')", consumer)+ ).rejects.toThrow('failed: exit code 1')+ })+})diff --git a/tools/release-packages/package.json b/tools/release-packages/package.jsonindex e7311e279..fc3fcf452 100644--- a/tools/release-packages/package.json+++ b/tools/release-packages/package.json@@ -4,8 +4,15 @@"type": "module","scripts": {"check-changelog": "bun src/check-changelog.ts",- "prepare-publish-dirs": "bun src/prepare-publish-dirs.ts",- "validate-tarballs": "bun src/validate-tarballs.ts",+ "build": "bun src/cli.ts build",+ "prepare-publish-dirs": "bun src/cli.ts prepare",+ "pack": "bun src/cli.ts pack",+ "publish": "bun src/cli.ts publish","test": "bun test tests"+ },+ "dependencies": {+ "@open-pencil/package-artifacts": "workspace:*",+ "@open-pencil/package-quality-tools": "workspace:*",+ "citty": "^0.1.6"}}diff --git a/tools/release-packages/src/cli.ts b/tools/release-packages/src/cli.tsnew file mode 100644index 000000000..5f638c2fc--- /dev/null+++ b/tools/release-packages/src/cli.ts@@ -0,0 +1,42 @@+#!/usr/bin/env bun++import { defineCommand, runMain } from 'citty'++import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts'++import {+ buildReleasePackages,+ packReleasePackages,+ prepareReleasePackages,+ publishReleasePackages+} from './workflow'++function command(name: string, description: string, execute: (root: string) => Promise<unknown>) {+ return defineCommand({+ meta: { name, description },+ args: { root: { type: 'string', description: 'Explicit workspace root' } },+ async run({ args }) {+ await execute(await resolveWorkspaceRoot(process.cwd(), args.root))+ }+ })+}++await runMain(+ defineCommand({+ meta: { name: 'release-packages', description: 'Build and publish verified npm packages' },+ subCommands: {+ build: command('build', 'Build public packages in dependency order', buildReleasePackages),+ prepare: command(+ 'prepare',+ 'Prepare transparent publish directories',+ prepareReleasePackages+ ),+ pack: command('pack', 'Pack and validate release package artifacts', packReleasePackages),+ publish: command(+ 'publish',+ 'Publish the exact verified package artifacts',+ publishReleasePackages+ )+ }+ })+)diff --git a/tools/release-packages/src/policy.ts b/tools/release-packages/src/policy.tsnew file mode 100644index 000000000..0f1805a3d--- /dev/null+++ b/tools/release-packages/src/policy.ts@@ -0,0 +1,6 @@+/** Official releases always target public npm with provenance; ambient npmrc cannot redirect them. */+export const NPM_RELEASE_POLICY = {+ access: 'public',+ provenance: true,+ registry: 'https://registry.npmjs.org/'+} as constdiff --git a/tools/release-packages/src/prepare-publish-dirs.ts b/tools/release-packages/src/prepare-publish-dirs.tsdeleted file mode 100644index f6f388074..000000000--- a/tools/release-packages/src/prepare-publish-dirs.ts+++ /dev/null@@ -1,18 +0,0 @@-import { readFile } from 'node:fs/promises'-import { join } from 'node:path'--import { DEFAULT_PACKAGES, preparePublishDirectories } from './publish-dirs'--const root = process.cwd()-const corePackageJSON = JSON.parse(- await readFile(join(root, 'packages/core/package.json'), 'utf8')-) as {- version: string-}--await preparePublishDirectories({- coreVersion: corePackageJSON.version,- packages: DEFAULT_PACKAGES,- root,- log: (message) => process.stdout.write(`${message}\n`)-})diff --git a/tools/release-packages/src/publish-dirs.ts b/tools/release-packages/src/publish-dirs.tsindex e7e97b26f..8fe0b7865 100644--- a/tools/release-packages/src/publish-dirs.ts+++ b/tools/release-packages/src/publish-dirs.ts@@ -1,13 +1,22 @@-import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'+import { cp, mkdir, rm, writeFile } from 'node:fs/promises'import { basename, dirname, join } from 'node:path'-interface PackagePublishConfig {- dir: string- extraFiles: string[]- include: string[]+import {+ discoverPublicPackages,+ parseNpmPack,+ readPackageManifest,+ runCommand,+ type PackageManifest,+ type WorkspacePackage+} from '@open-pencil/package-artifacts'++import { NPM_RELEASE_POLICY } from './policy'++export interface PackagePublishConfig {+ directory: string}-interface PreparePublishDirectoriesOptions {+export interface PreparePublishDirectoriesOptions {coreVersion: stringpackages: PackagePublishConfig[]root: string@@ -15,78 +24,34 @@ interface PreparePublishDirectoriesOptions {log?: (message: string) => void}-type PackageJSON = Record<string, unknown> & {- dependencies?: Record<string, string>- devDependencies?: Record<string, string>- peerDependencies?: Record<string, string>- publishConfig?: Record<string, unknown>- scripts?: unknown-}--const PACKAGE_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies'] as const+const PACKAGE_FIELDS = [+ 'dependencies',+ 'devDependencies',+ 'peerDependencies',+ 'optionalDependencies'+] as const satisfies ReadonlyArray<keyof PackageManifest>const PUBLISH_CONFIG_FIELDS = new Set(['access', 'provenance', 'registry'])-export const DEFAULT_PACKAGES: PackagePublishConfig[] = [- { dir: 'packages/scene-graph', include: ['dist'], extraFiles: ['README.md'] },- { dir: 'packages/pen', include: ['dist'], extraFiles: ['README.md'] },- { dir: 'packages/kiwi', include: ['dist'], extraFiles: ['README.md'] },- { dir: 'packages/fig', include: ['dist'], extraFiles: ['README.md'] },- { dir: 'packages/core', include: ['dist', 'src', 'assets'], extraFiles: [] },- { dir: 'packages/dom-css', include: ['dist'], extraFiles: ['README.md'] },- { dir: 'packages/cli', include: ['bin', 'dist'], extraFiles: [] },- { dir: 'packages/mcp', include: ['dist'], extraFiles: [] },- { dir: 'packages/harness', include: ['dist'], extraFiles: ['README.md'] },- { dir: 'packages/vue', include: ['dist'], extraFiles: ['README.md'] }-]--async function exists(path: string) {- try {- await stat(path)- return true- } catch {- return false- }-}--async function copyRecursive(from: string, to: string): Promise<void> {- const sourceStat = await stat(from)- if (sourceStat.isDirectory()) {- await mkdir(to, { recursive: true })- for (const entry of await readdir(from)) {- await copyRecursive(join(from, entry), join(to, entry))+export function publishPackageJSON(source: PackageManifest, coreVersion: string): PackageManifest {+ if (source.publishConfig) {+ for (const [field, expected] of Object.entries(NPM_RELEASE_POLICY)) {+ if (field in source.publishConfig && source.publishConfig[field] !== expected) {+ throw new Error(+ `${source.name}: publishConfig.${field} conflicts with the public npm release policy`+ )+ }}- return}-- await mkdir(dirname(to), { recursive: true })- await copyFile(from, to)-}--interface PackageExports {- [key: string]: PackageExports | string | undefined-}--interface PublishPackageJSON extends PackageJSON {- exports?: PackageExports- imports?: PackageExports-}--function isPackageExports(value: unknown): value is PackageExports {- return typeof value === 'object' && value !== null && !Array.isArray(value)-}--function removeUnpublishedConditions(value: PackageExports | undefined): void {- if (!value) return- delete value.bun- for (const child of Object.values(value)) {- if (isPackageExports(child)) removeUnpublishedConditions(child)+ const json = structuredClone(source)+ for (const field of ['exports', 'imports', 'main', 'types', 'bin'] as const) {+ if (+ source.publishConfig &&+ field in source.publishConfig &&+ JSON.stringify(source.publishConfig[field]) !== JSON.stringify(source[field])+ ) {+ throw new Error(`${source.name}: publishConfig must not rewrite ${field}`)+ }}-}--export function publishPackageJSON(source: PackageJSON, coreVersion: string): PackageJSON {- const json = structuredClone(source) as PublishPackageJSON- removeUnpublishedConditions(json.exports)- removeUnpublishedConditions(json.imports)for (const field of PACKAGE_FIELDS) {const dependencies = json[field]@@ -109,38 +74,45 @@ export function publishPackageJSON(source: PackageJSON, coreVersion: string): Pareturn json}+export function packagePublishConfig(pkg: WorkspacePackage): PackagePublishConfig {+ return { directory: pkg.directory }+}++export async function discoverPublishPackages(root: string): Promise<PackagePublishConfig[]> {+ return (await discoverPublicPackages(root)).map(packagePublishConfig)+}+export async function preparePublishDirectories(options: PreparePublishDirectoriesOptions): Promise<void> {const outRoot = options.outRoot ?? join(options.root, '.publish')- const log = options.log-await rm(outRoot, { recursive: true, force: true })await mkdir(outRoot, { recursive: true })for (const pkg of options.packages) {- const sourceDir = join(options.root, pkg.dir)- const destinationDir = join(outRoot, basename(pkg.dir))+ const sourceDir = join(options.root, pkg.directory)+ const destinationDir = join(outRoot, basename(pkg.directory))await mkdir(destinationDir, { recursive: true })- for (const relativePath of pkg.include) {- const from = join(sourceDir, relativePath)- if (await exists(from)) await copyRecursive(from, join(destinationDir, relativePath))- }-- for (const relativePath of pkg.extraFiles) {- const from = join(sourceDir, relativePath)- if (await exists(from)) await copyRecursive(from, join(destinationDir, relativePath))+ const listing = await runCommand({+ command: 'npm',+ args: ['pack', '--dry-run', '--json', '--ignore-scripts'],+ cwd: sourceDir,+ timeoutMs: 60_000+ })+ const files = parseNpmPack(listing.stdout).files+ for (const relativePath of files) {+ const destination = join(destinationDir, relativePath)+ await mkdir(dirname(destination), { recursive: true })+ await cp(join(sourceDir, relativePath), destination, { dereference: false })}- const packageJSON = JSON.parse(- await readFile(join(sourceDir, 'package.json'), 'utf8')- ) as PackageJSON+ const packageJSON = await readPackageManifest(join(sourceDir, 'package.json'))const publishJSON = publishPackageJSON(packageJSON, options.coreVersion)await writeFile(join(destinationDir, 'package.json'),`${JSON.stringify(publishJSON, null, 2)}\n`)- log?.(`Prepared ${destinationDir}`)+ options.log?.(`Prepared ${destinationDir}`)}}diff --git a/tools/release-packages/src/tarballs.ts b/tools/release-packages/src/tarballs.tsdeleted file mode 100644index de9d29f2e..000000000--- a/tools/release-packages/src/tarballs.ts+++ /dev/null@@ -1,92 +0,0 @@-import { execFile } from 'node:child_process'-import { readdir } from 'node:fs/promises'-import { join } from 'node:path'-import { promisify } from 'node:util'--const execFileAsync = promisify(execFile)--type PackageExports = {- [key: string]: PackageExports | string | null | undefined-}--type PackageJSON = {- bin?: Record<string, string> | string- exports?: PackageExports- name: string-}--export function packageBinTargets(packageJSON: PackageJSON): Record<string, string> {- if (typeof packageJSON.bin === 'string') return { [packageJSON.name]: packageJSON.bin }- return packageJSON.bin ?? {}-}--function packageExportTargets(value: unknown): string[] {- if (typeof value === 'string') return [value]- if (Array.isArray(value)) return value.flatMap(packageExportTargets)- if (!value || typeof value !== 'object') return []- return Object.values(value).flatMap(packageExportTargets)-}--export function packageExportTargetPaths(packageJSON: Pick<PackageJSON, 'exports'>): string[] {- return packageExportTargets(packageJSON.exports)-}--export async function tarballEntries(tarballPath: string): Promise<Set<string>> {- const { stdout } = await execFileAsync('tar', ['-tf', tarballPath], { encoding: 'utf8' })- return new Set(stdout.trim().split('\n').filter(Boolean))-}--export async function tarballPackageJSON(tarballPath: string): Promise<PackageJSON> {- const { stdout } = await execFileAsync('tar', ['-xOf', tarballPath, 'package/package.json'], {- encoding: 'utf8'- })- return JSON.parse(stdout) as PackageJSON-}--export async function validateTarballBinTargets(tarballPath: string): Promise<void> {- const entries = await tarballEntries(tarballPath)- const packageJSON = await tarballPackageJSON(tarballPath)-- for (const [name, target] of Object.entries(packageBinTargets(packageJSON))) {- const entry = `package/${target.replace(/^\.\//, '')}`- if (!entries.has(entry)) {- throw new Error(`${tarballPath}: bin ${name} target missing from tarball: ${entry}`)- }- }-}--function exportTargetPattern(target: string): RegExp {- const escaped = target.replace(/[.+?^${}()|[\]\\]/g, '\\$&')- return new RegExp(`^${escaped.replace(/\*/g, '.*')}$`)-}-export async function validateTarballExportTargets(tarballPath: string): Promise<void> {- const entries = await tarballEntries(tarballPath)- const packageJSON = await tarballPackageJSON(tarballPath)-- for (const target of packageExportTargetPaths(packageJSON)) {- if (!target.startsWith('./')) continue- const relativeTarget = target.slice(2)- let matchingEntries: string[]- if (relativeTarget.includes('*')) {- const pattern = exportTargetPattern(relativeTarget)- matchingEntries = [...entries].filter((entry) => pattern.test(entry.slice('package/'.length)))- } else {- const exactEntry = `package/${relativeTarget}`- matchingEntries = entries.has(exactEntry) ? [exactEntry] : []- }- if (matchingEntries.length === 0) {- throw new Error(- `${tarballPath}: export target missing from tarball: package/${relativeTarget}`- )- }- }-}--export async function validatePackedTarballs(directory: string): Promise<void> {- const tarballs = (await readdir(directory)).filter((name) => name.endsWith('.tgz'))- for (const tarball of tarballs) {- const path = join(directory, tarball)- await validateTarballBinTargets(path)- await validateTarballExportTargets(path)- }-}diff --git a/tools/release-packages/src/validate-tarballs.ts b/tools/release-packages/src/validate-tarballs.tsdeleted file mode 100644index 158499b2f..000000000--- a/tools/release-packages/src/validate-tarballs.ts+++ /dev/null@@ -1,3 +0,0 @@-import { validatePackedTarballs } from './tarballs'--await validatePackedTarballs('.npm-packages')diff --git a/tools/release-packages/src/workflow.ts b/tools/release-packages/src/workflow.tsnew file mode 100644index 000000000..1a9cd60ea--- /dev/null+++ b/tools/release-packages/src/workflow.ts@@ -0,0 +1,206 @@+import { mkdir, readdir, rm } from 'node:fs/promises'+import { basename, join } from 'node:path'++import {+ buildPublicPackages,+ CommandError,+ discoverPublicPackages,+ orderPackagesByDependencies,+ parseNpmPack,+ isRegistryNotFound,+ validateRegistryVersion,+ readPackageManifest,+ runCommand,+ type WorkspacePackage+} from '@open-pencil/package-artifacts'+import { inspectTarball, validatePackedTarballs } from '@open-pencil/package-artifacts/tarball'+import { verifyArtifactConsumers } from '@open-pencil/package-quality-tools/consumer'++import { NPM_RELEASE_POLICY } from './policy'+import { discoverPublishPackages, preparePublishDirectories } from './publish-dirs'++export interface PublicationPlanEntry {+ package: WorkspacePackage+ status: 'published' | 'unpublished'+}++export type PackagePublicationLookup = (pkg: WorkspacePackage) => Promise<boolean>++export interface ReleasePaths {+ artifacts: string+ prepared: string+ root: string+}++export function releasePaths(root: string): ReleasePaths {+ return {+ root,+ artifacts: join(root, '.npm-packages'),+ prepared: join(root, '.publish')+ }+}++export { buildPublicPackages as buildReleasePackages }++export async function prepareReleasePackages(root: string): Promise<void> {+ const packages = await discoverPublicPackages(root)+ const { version } = await readPackageManifest(join(root, 'package.json'))+ if (packages.length === 0) throw new Error('No public packages discovered')+ if (packages.some(({ manifest }) => manifest.version !== version)) {+ throw new Error('Public package versions must be aligned before release preparation')+ }+ await preparePublishDirectories({+ coreVersion: version,+ packages: await discoverPublishPackages(root),+ root,+ log: console.log+ })+}++async function packageIsPublished(pkg: WorkspacePackage, root: string): Promise<boolean> {+ const specifier = `${pkg.manifest.name}@${pkg.manifest.version}`+ try {+ const result = await runCommand({+ command: 'npm',+ args: ['view', specifier, 'version', '--json', '--registry', NPM_RELEASE_POLICY.registry],+ cwd: root,+ timeoutMs: 30_000+ })+ validateRegistryVersion(result.stdout, pkg.manifest.version)+ return true+ } catch (error) {+ if (error instanceof CommandError && isRegistryNotFound(error.stdout)) return false+ throw error+ }+}++export async function createPublicationPlan(+ root: string,+ isPublished: PackagePublicationLookup = (pkg) => packageIsPublished(pkg, root)+): Promise<PublicationPlanEntry[]> {+ const packages = orderPackagesByDependencies(await discoverPublicPackages(root))+ const statuses = await Promise.all(packages.map(isPublished))+ return packages.map((pkg, index) => ({+ package: pkg,+ status: statuses[index] ? 'published' : 'unpublished'+ }))+}++export async function packReleasePackages(+ root: string,+ isPublished?: PackagePublicationLookup+): Promise<PublicationPlanEntry[]> {+ const paths = releasePaths(root)+ const plan = await createPublicationPlan(root, isPublished)+ await rm(paths.artifacts, { recursive: true, force: true })+ await mkdir(paths.artifacts, { recursive: true })++ for (const entry of plan) {+ const { manifest } = entry.package+ const preparedDirectory = join(paths.prepared, basename(entry.package.directory))+ const result = await runCommand({+ command: 'npm',+ args: ['pack', '--json', '--pack-destination', paths.artifacts],+ cwd: preparedDirectory,+ timeoutMs: 60_000+ })+ console.log(`Packed ${manifest.name}: ${parseNpmPack(result.stdout).filename}`)+ }++ await validatePackedTarballs(paths.artifacts)+ return plan+}++async function artifactsByPackage(directory: string): Promise<Map<string, string>> {+ const artifacts = new Map<string, string>()+ for (const filename of (await readdir(directory)).filter((name) => name.endsWith('.tgz'))) {+ const path = join(directory, filename)+ const { manifest, diagnostics } = await inspectTarball(path)+ if (diagnostics.length > 0) {+ throw new Error(+ diagnostics+ .map(({ packageName, field, message }) => `${packageName}: ${field} ${message}`)+ .join('\n')+ )+ }+ const key = `${manifest.name}@${manifest.version}`+ if (artifacts.has(key)) throw new Error(`Duplicate package artifact for ${key}`)+ artifacts.set(key, path)+ }+ return artifacts+}++export function validatePublicationArtifacts(+ plan: PublicationPlanEntry[],+ artifacts: Map<string, string>+): void {+ const expected = new Set(+ plan+ .filter(({ status }) => status === 'unpublished')+ .map(({ package: pkg }) => `${pkg.manifest.name}@${pkg.manifest.version}`)+ )+ const missing = [...expected].filter((key) => !artifacts.has(key))+ const known = new Set(+ plan.map(({ package: pkg }) => `${pkg.manifest.name}@${pkg.manifest.version}`)+ )+ const unexpected = [...artifacts.keys()].filter((key) => !known.has(key))+ if (missing.length === 0 && unexpected.length === 0) return++ const messages = [+ ...missing.map((key) => `Missing verified package artifact for ${key}`),+ ...unexpected.map((key) => `Unexpected package artifact for ${key}`)+ ]+ throw new Error(messages.join('\n'))+}++export interface PublicationOperations {+ plan(root: string): Promise<PublicationPlanEntry[]>+ artifacts(directory: string): Promise<Map<string, string>>+ verify(root: string, tarballs: string[]): Promise<void>+ execute: typeof runCommand+}++const publicationOperations: PublicationOperations = {+ plan: createPublicationPlan,+ artifacts: artifactsByPackage,+ verify: verifyArtifactConsumers,+ execute: runCommand+}++export async function publishReleasePackages(+ root: string,+ operations: PublicationOperations = publicationOperations+): Promise<PublicationPlanEntry[]> {+ const paths = releasePaths(root)+ const plan = await operations.plan(root)+ const artifacts = await operations.artifacts(paths.artifacts)+ validatePublicationArtifacts(plan, artifacts)+ await operations.verify(root, [...artifacts.values()])++ for (const entry of plan) {+ const { manifest } = entry.package+ if (entry.status === 'published') {+ console.log(`Skipping ${manifest.name}@${manifest.version}: already published`)+ continue+ }+ const key = `${manifest.name}@${manifest.version}`+ const artifact = artifacts.get(key)+ if (!artifact) throw new Error(`Publication artifact disappeared for ${key}`)+ await operations.execute({+ command: 'npm',+ args: [+ 'publish',+ artifact,+ '--access',+ NPM_RELEASE_POLICY.access,+ '--provenance',+ '--registry',+ NPM_RELEASE_POLICY.registry+ ],+ cwd: root,+ output: 'inherit',+ timeoutMs: 120_000+ })+ }+ return plan+}diff --git a/tools/release-packages/tests/publication.test.ts b/tools/release-packages/tests/publication.test.tsnew file mode 100644index 000000000..3e6c50e1d--- /dev/null+++ b/tools/release-packages/tests/publication.test.ts@@ -0,0 +1,75 @@+import { expect, test } from 'bun:test'++import {+ publishReleasePackages,+ type PublicationOperations,+ type PublicationPlanEntry+} from '../src/workflow'++function fixture() {+ const plan: PublicationPlanEntry[] = ['one', 'two'].map((name) => ({+ package: { directory: name, manifest: { name, version: '1.0.0' } },+ status: 'unpublished'+ }))+ const published: string[][] = []+ const artifacts = new Map([+ ['[email protected]', '/one.tgz'],+ ['[email protected]', '/two.tgz']+ ])+ const operations: PublicationOperations = {+ plan: async () => plan,+ artifacts: async () => artifacts,+ verify: async (_root, paths) => {+ expect(paths).toHaveLength(2)+ },+ execute: async ({ args }) => {+ published.push(args ?? [])+ return { stdout: '', stderr: '' }+ }+ }+ return { plan, published, artifacts, operations }+}++test('verification failure prevents every registry write', async () => {+ const state = fixture()+ state.operations.verify = async () => {+ throw new Error('broken consumer')+ }+ await expect(publishReleasePackages('/repo', state.operations)).rejects.toThrow('broken consumer')+ expect(state.published).toEqual([])+})++test('a partial retry verifies retained artifacts and publishes only pending versions', async () => {+ const state = fixture()+ const first = state.plan[0]+ if (!first) throw new Error('Missing fixture entry')+ first.status = 'published'+ let verified = false+ state.operations.verify = async (_root, artifacts) => {+ expect(artifacts).toEqual(['/one.tgz', '/two.tgz'])+ verified = true+ }+ state.operations.execute = async ({ args }) => {+ expect(verified).toBe(true)+ state.published.push(args ?? [])+ return { stdout: '', stderr: '' }+ }+ await publishReleasePackages('/repo', state.operations)+ expect(state.published).toHaveLength(1)+ expect(state.published[0]).toContain('/two.tgz')+})++test('mismatched artifacts prevent verification and publication', async () => {+ const state = fixture()+ state.artifacts.delete('[email protected]')+ state.artifacts.set('[email protected]', '/wrong.tgz')+ let verified = false+ state.operations.verify = async () => {+ verified = true+ }+ await expect(publishReleasePackages('/repo', state.operations)).rejects.toThrow(+ 'Missing verified package artifact'+ )+ expect(verified).toBe(false)+ expect(state.published).toEqual([])+})diff --git a/tools/release-packages/tests/publish-dirs.test.ts b/tools/release-packages/tests/publish-dirs.test.tsindex 03439facb..73df817c1 100644--- a/tools/release-packages/tests/publish-dirs.test.ts+++ b/tools/release-packages/tests/publish-dirs.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import {- DEFAULT_PACKAGES,+ discoverPublishPackages,preparePublishDirectories,publishPackageJSON} from '../src/publish-dirs'@@ -13,17 +13,25 @@ async function fixtureRoot() {const root = join(tmpdir(), `open-pencil-release-packages-${crypto.randomUUID()}`)await mkdir(join(root, 'packages/example/dist'), { recursive: true })await writeFile(join(root, 'packages/example/dist/index.js'), 'export {}\n')+ await writeFile(join(root, 'packages/example/README.md'), '# Example\n')+ await writeFile(join(root, 'packages/example/LICENSE'), 'fixture license\n')+ await writeFile(join(root, 'package.json'), JSON.stringify({ workspaces: ['packages/example'] }))await writeFile(join(root, 'packages/example/package.json'),JSON.stringify({name: '@open-pencil/example',version: '1.0.0',+ files: ['dist', 'README.md'],scripts: { build: 'tsdown' },dependencies: { '@open-pencil/core': 'workspace:*', zod: '^4.0.0' },- exports: { '.': { bun: './src/index.ts', import: './dist/index.js' } },+ exports: {+ '.': { bun: './dist/index.js', import: './dist/index.js' }+ },devDependencies: { typescript: '^5.0.0' },- publishConfig: { access: 'public', main: './dist/index.js', types: './dist/index.d.ts' }+ main: './dist/index.js',+ types: './dist/index.d.ts',+ publishConfig: { access: 'public' }},null,2@@ -33,63 +41,86 @@ async function fixtureRoot() {}describe('publishPackageJSON', () => {- test('rewrites workspace dependencies and strips private build fields', () => {+ test('rejects conflicting publication settings', () => {+ for (const publishConfig of [+ { access: 'restricted' },+ { provenance: false },+ { registry: 'https://other.invalid/' }+ ]) {+ expect(() =>+ publishPackageJSON({ name: 'fixture', version: '1.0.0', publishConfig }, '1.0.0')+ ).toThrow('conflicts with the public npm release policy')+ }+ })++ test('rejects resolution rewrites even when injected through publishConfig', () => {+ expect(() =>+ publishPackageJSON(+ {+ name: '@fixture/example',+ version: '1.0.0',+ exports: { '.': './dist/index.js' },+ publishConfig: { exports: { '.': './missing.js' } }+ },+ '1.0.0'+ )+ ).toThrow('publishConfig must not rewrite exports')+ })++ test('rewrites workspace dependencies without changing runtime exports', () => {+ const exports = { '.': { bun: './dist/index.js', import: './dist/index.js' } }const json = publishPackageJSON({name: '@open-pencil/example',+ version: '1.0.0',scripts: { build: 'tsdown' },dependencies: { '@open-pencil/core': 'workspace:*', zod: '^4.0.0' },- exports: { '.': { bun: './src/index.ts', import: './dist/index.js' } },+ exports,devDependencies: { typescript: '^5.0.0' },- publishConfig: { access: 'public', main: './dist/index.js' }+ main: './dist/index.js',+ publishConfig: { access: 'public' }},'0.13.2')expect(json).toEqual({name: '@open-pencil/example',+ version: '1.0.0',dependencies: { '@open-pencil/core': '^0.13.2', zod: '^4.0.0' },- exports: { '.': { import: './dist/index.js' } },+ exports,main: './dist/index.js'})})})-describe('DEFAULT_PACKAGES', () => {- test('includes every public workspace package that release publish must pack', () => {- expect(DEFAULT_PACKAGES.map((pkg) => pkg.dir)).toEqual([- 'packages/scene-graph',- 'packages/pen',- 'packages/kiwi',- 'packages/fig',- 'packages/core',- 'packages/dom-css',- 'packages/cli',- 'packages/mcp',- 'packages/harness',- 'packages/vue'- ])+describe('discoverPublishPackages', () => {+ test('derives release contents from public workspace manifests', async () => {+ const root = await fixtureRoot()+ expect(await discoverPublishPackages(root)).toEqual([{ directory: 'packages/example' }])})})describe('preparePublishDirectories', () => {- test('copies requested files and writes publish package metadata', async () => {+ test('copies declared artifacts and writes transformed package metadata', async () => {const root = await fixtureRoot()const outRoot = join(root, '.publish')await preparePublishDirectories({coreVersion: '0.13.2',outRoot,- packages: [{ dir: 'packages/example', include: ['dist'], extraFiles: [] }],+ packages: await discoverPublishPackages(root),root})expect(await readFile(join(outRoot, 'example/dist/index.js'), 'utf8')).toBe('export {}\n')+ expect(await readFile(join(outRoot, 'example/LICENSE'), 'utf8')).toBe('fixture license\n')+ expect(await readFile(join(outRoot, 'example/README.md'), 'utf8')).toBe('# Example\n')expect(JSON.parse(await readFile(join(outRoot, 'example/package.json'), 'utf8'))).toEqual({name: '@open-pencil/example',version: '1.0.0',+ files: ['dist', 'README.md'],dependencies: { '@open-pencil/core': '^0.13.2', zod: '^4.0.0' },- exports: { '.': { import: './dist/index.js' } },+ exports: { '.': { bun: './dist/index.js', import: './dist/index.js' } },main: './dist/index.js',types: './dist/index.d.ts'})diff --git a/tools/release-packages/tests/tarballs.test.ts b/tools/release-packages/tests/tarballs.test.tsdeleted file mode 100644index 1a68d3d1a..000000000--- a/tools/release-packages/tests/tarballs.test.ts+++ /dev/null@@ -1,44 +0,0 @@-import { describe, expect, test } from 'bun:test'--import { packageBinTargets, packageExportTargetPaths } from '../src/tarballs'--describe('packageBinTargets', () => {- test('normalizes string bin fields', () => {- expect(packageBinTargets({ name: '@open-pencil/cli', bin: './bin/openpencil.js' })).toEqual({- '@open-pencil/cli': './bin/openpencil.js'- })- })-- test('keeps named bin fields', () => {- expect(- packageBinTargets({ name: '@open-pencil/cli', bin: { openpencil: './bin/openpencil.js' } })- ).toEqual({- openpencil: './bin/openpencil.js'- })- })-})--describe('package export targets', () => {- test('collects wildcard targets from conditional exports', () => {- expect(- packageExportTargetPaths({ exports: { './feature/*': { import: './dist/*.js' } } })- ).toEqual(['./dist/*.js'])- })-- test('collects nested wildcard targets from conditional exports', () => {- expect(- packageExportTargetPaths({ exports: { './feature/*': { import: './dist/*.js' } } })- ).toEqual(['./dist/*.js'])- })-- test('collects targets from conditional exports', () => {- expect(- packageExportTargetPaths({- exports: {- '.': { types: './dist/index.d.ts', import: './dist/index.js' },- './feature': { import: './dist/feature.js' }- }- })- ).toEqual(['./dist/index.d.ts', './dist/index.js', './dist/feature.js'])- })-})diff --git a/tools/release-packages/tests/workflow.test.ts b/tools/release-packages/tests/workflow.test.tsnew file mode 100644index 000000000..d19c58ce3--- /dev/null+++ b/tools/release-packages/tests/workflow.test.ts@@ -0,0 +1,134 @@+import { describe, expect, test } from 'bun:test'+import { mkdir, readdir, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import {+ buildReleasePackages,+ createPublicationPlan,+ packReleasePackages,+ prepareReleasePackages,+ releasePaths,+ validatePublicationArtifacts+} from '../src/workflow'++async function createWorkspace() {+ const root = join(tmpdir(), `open-pencil-release-workflow-${crypto.randomUUID()}`)+ await mkdir(join(root, 'packages/library'), { recursive: true })+ await mkdir(join(root, 'packages/app'), { recursive: true })+ await writeFile(+ join(root, 'package.json'),+ JSON.stringify({ workspaces: ['packages/app', 'packages/library'] })+ )+ await writeFile(+ join(root, 'packages/library/package.json'),+ JSON.stringify({+ name: '@fixture/library',+ version: '1.0.0',+ scripts: { build: "bun -e \"await Bun.write('../../order.txt', 'library')\"" }+ })+ )+ await writeFile(+ join(root, 'packages/app/package.json'),+ JSON.stringify({+ name: '@fixture/app',+ version: '1.0.0',+ dependencies: { '@fixture/library': 'workspace:*' },+ scripts: {+ build:+ "bun -e \"const previous = await Bun.file('../../order.txt').text(); await Bun.write('../../order.txt', previous + ',app')\""+ }+ })+ )+ return root+}++describe('release workflow', () => {+ test('uses conventional release artifact locations', () => {+ expect(releasePaths('/repo')).toEqual({+ root: '/repo',+ artifacts: '/repo/.npm-packages',+ prepared: '/repo/.publish'+ })+ })++ test('creates a dependency-ordered publication plan from registry results', async () => {+ const root = await createWorkspace()+ const plan = await createPublicationPlan(+ root,+ async ({ manifest }) => manifest.name === '@fixture/library'+ )+ expect(plan.map(({ package: pkg, status }) => ({ name: pkg.manifest.name, status }))).toEqual([+ { name: '@fixture/library', status: 'published' },+ { name: '@fixture/app', status: 'unpublished' }+ ])+ })++ test('rejects incomplete or stale artifact sets before publication', () => {+ const packageEntry = {+ directory: 'packages/example',+ manifest: { name: '@fixture/example', version: '1.0.0' }+ }+ expect(() =>+ validatePublicationArtifacts([{ package: packageEntry, status: 'unpublished' }], new Map())+ ).toThrow('Missing verified package artifact for @fixture/[email protected]')+ expect(() =>+ validatePublicationArtifacts(+ [{ package: packageEntry, status: 'published' }],+ new Map([['@fixture/[email protected]', '/artifact.tgz']])+ )+ ).not.toThrow()+ expect(() =>+ validatePublicationArtifacts([], new Map([['@fixture/[email protected]', '/artifact.tgz']]))+ ).toThrow('Unexpected package artifact for @fixture/[email protected]')+ })++ test('packs and validates an unpublished release artifact', async () => {+ const root = join(tmpdir(), `open-pencil-release-pack-${crypto.randomUUID()}`)+ await mkdir(join(root, 'packages/example/dist'), { recursive: true })+ await writeFile(+ join(root, 'package.json'),+ JSON.stringify({ name: 'fixture', version: '1.0.0', workspaces: ['packages/example'] })+ )+ await writeFile(join(root, 'packages/example/dist/index.js'), 'export const ready = true\n')+ await writeFile(+ join(root, 'packages/example/dist/index.d.ts'),+ 'export declare const ready: true\n'+ )+ await writeFile(+ join(root, 'packages/example/package.json'),+ JSON.stringify({+ name: '@fixture/release-package',+ version: '1.0.0',+ files: ['dist'],+ exports: {+ '.': {+ types: './dist/index.d.ts',+ import: './dist/index.js',+ default: './dist/index.js'+ }+ },+ publishConfig: { access: 'public' }+ })+ )++ await prepareReleasePackages(root)+ const plan = await packReleasePackages(root, async () => false)+ expect(plan.map(({ package: pkg, status }) => [pkg.manifest.name, status])).toEqual([+ ['@fixture/release-package', 'unpublished']+ ])+ expect(+ (await readdir(releasePaths(root).artifacts)).filter((name) => name.endsWith('.tgz'))+ ).toHaveLength(1)+ })++ test('builds discovered packages in dependency order', async () => {+ const root = await createWorkspace()+ const packages = await buildReleasePackages(root, { output: 'capture' })+ expect(packages.map(({ manifest }) => manifest.name)).toEqual([+ '@fixture/library',+ '@fixture/app'+ ])+ expect(await Bun.file(join(root, 'order.txt')).text()).toBe('library,app')+ })+})