/** * Follows `npx foldkit-plus setup` the way a user on npm meets it, against the * packed tarballs (#200, #205, #229). Run after `pnpm pack`, which leaves each * tarball beside its manifest; everything not ours comes from the registry. * * 1. The CLI from its tarball, alone, beneath an ancestor `node_modules/effect` * that throws when loaded: npx with `--legacy-peer-deps` installs no peer, * and Node would walk up to it. * 2. In an empty folder the guide prints the scaffold commands: run the one for * the rendering mode, with the package manager, as printed. * 3. In the scaffold, every npm step the guide prints: the `package.json` * fields, the install line, then each adapter's line. Each must exit 0 with * no ERESOLVE, even as a warning, and leave one `effect` and one `foldkit`, * with nothing of Effect's, Foldkit's or ours that `npm ls` calls invalid. * With pnpm, the pins and the install line, as in 5. * 4. The scaffold's own `lint` and `typecheck` scripts over what it drew and a * module importing every entry point of `foldkit-plus`, so our types meet * the scaffold's compiler options and its Effect; the examples are copied * in first, as a reader copies them, their imports rewritten to * `foldkit-plus/…` as an app on the meta package writes them, so one * `typecheck` and one `lint` cover them too, but for their `demo.ts` files: * a demo harness stands in for a person, sending a child's input Messages * on purpose. * 5. With no options, pnpm's pins and install lines also run in a standalone * project and a workspace member, over a stand-in manifest. * * A step names our packages bare; this runs it with each one's tarball, and * points every other reference to one of ours at its tarball with `overrides`, * so an unpublished version resolves. The adapters' lines and the stand-ins * run only for the default, an ssr scaffold with npm; the `pack` CI job runs * that, and a matrix job each other pair. * * node scripts/published-setup.mjs [--rendering spa|ssg|ssr] [--manager npm|pnpm] [tarball-dir] */ import { spawnSync } from 'node:child_process' import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' const root = fileURLToPath(new URL('..', import.meta.url)) const args = process.argv.slice(2) const option = (name, values) => { const at = args.indexOf(name) if (at === -1) return values[0] const [value] = args.splice(at, 2).slice(1) if (!values.includes(value)) throw new Error(`${name} takes ${values.join(', ')}`) return value } const rendering = option('--rendering', ['ssr', 'spa', 'ssg']) const manager = option('--manager', ['npm', 'pnpm']) const full = rendering === 'ssr' && manager === 'npm' /** Each of our packages' name, to its tarball. */ const tarballs = new Map() const given = args[0] if (given === undefined) { for (const dir of readdirSync(join(root, 'packages'))) { const manifest = join(root, 'packages', dir, 'package.json') if (!existsSync(manifest)) continue const { name, version, private: unpublished } = JSON.parse(readFileSync(manifest, 'utf8')) if (unpublished) continue const file = join(root, 'packages', dir, `${name}-${version}.tgz`) if (!existsSync(file)) throw new Error(`${file} is missing: run pnpm pack first`) tarballs.set(name, file) } } else { for (const file of readdirSync(given)) { const named = /^(.+)-\d+\.\d+\.\d+.*\.tgz$/.exec(file) if (named !== null) tarballs.set(named[1], join(given, file)) } } if (!tarballs.has('foldkit-plus')) throw new Error('No foldkit-plus tarball') const work = mkdtempSync(join(tmpdir(), 'foldkit-plus-setup-')) const home = join(work, 'home') // A new user's cache: nothing installed by an earlier run is reused. The // user agent is what npx gives the CLI, which reads it for the manager; run // under `pnpm pack:check`, it would otherwise say pnpm. const env = { ...process.env, npm_config_user_agent: `npm/11 node/${process.version}`, npm_config_cache: join(work, 'npm-cache'), npm_config_audit: 'false', npm_config_fund: 'false', npm_config_update_notifier: 'false', } const fail = message => { console.error(`published-setup: ${message}\n(left in ${work})`) process.exit(1) } /** Runs a shell command, as a user would type it, and returns its output. */ const run = (command, cwd) => { const result = spawnSync(command, { cwd, env, shell: true, encoding: 'utf8' }) return { status: result.status, stdout: result.stdout, output: `${result.stdout}${result.stderr}`, } } // 1. The CLI, unpacked as npx would leave it but with nothing beside it. const tools = join(home, 'tools') mkdirSync(tools, { recursive: true }) copyFileSync(tarballs.get('foldkit-plus'), join(tools, 'plus.tgz')) if (run('tar -xzf plus.tgz', tools).status !== 0) fail('could not unpack foldkit-plus') // The skill and the guides ship in the tarball, and no design note does. const listing = run('tar -tzf plus.tgz', tools) if (listing.status !== 0) fail('could not list foldkit-plus') const shipped = listing.stdout.split(/\r?\n/) for (const [what, pattern] of [ ['skill/SKILL.md', /^package\/skill\/SKILL\.md$/], ['a skill reference', /^package\/skill\/references\/[^/]+\.md$/], ['a guide', /^package\/guides\/[^/]+\.md$/], ]) if (!shipped.some(path => pattern.test(path))) fail(`the foldkit-plus tarball has no ${what}`) const designs = shipped.filter(path => /docs\/design|guides\/design/.test(path)) if (designs.length > 0) fail(`the foldkit-plus tarball holds design notes: ${designs.join(', ')}`) mkdirSync(join(tools, 'node_modules')) renameSync(join(tools, 'package'), join(tools, 'node_modules', 'foldkit-plus')) const cli = join(tools, 'node_modules', 'foldkit-plus', 'dist', 'cli.mjs') const stranger = join(home, 'node_modules', 'effect') mkdirSync(stranger, { recursive: true }) writeFileSync( join(stranger, 'package.json'), JSON.stringify({ name: 'effect', version: '3.19.8', type: 'module', exports: './index.js' }), ) writeFileSync(join(stranger, 'index.js'), "throw new Error('the ancestor effect was loaded')\n") /** The guide for `cwd`, run as `agent` (pnpm's `dlx` gives its own) would run it. */ const setup = (cwd, agent = env.npm_config_user_agent) => { const result = spawnSync(process.execPath, [cli, 'setup'], { cwd, env: { ...env, npm_config_user_agent: agent }, encoding: 'utf8', }) if (result.status !== 0 || !result.stdout.startsWith('# Foldkit Plus')) fail(`setup failed in ${cwd}:\n${result.stdout}${result.stderr}`) return result.stdout } const pnpmAgent = `pnpm/10.32.1 npm/? node/${process.version}` const agent = manager === 'pnpm' ? pnpmAgent : env.npm_config_user_agent // 2. The scaffold. const empty = join(home, 'new') mkdirSync(empty) const printed = new RegExp( `^npx (?:--force )?create-foldkit-app@\\S+ .*--rendering ${rendering} .*--package-manager ${manager}$`, ) const scaffold = setup(empty, agent) .split('\n') .find(line => printed.test(line)) if (scaffold === undefined) fail(`the guide prints no ${rendering} scaffold command for ${manager}`) const created = run(scaffold.replace('', 'app'), empty) if (created.status !== 0) fail(`${scaffold} failed:\n${created.output}`) const app = join(empty, 'app') /** * Examples a reader copies into an app (#229). Each needs only `foldkit-plus` * and Effect: one that needs an optional adapter (`foldkit-mixins-ui` and * `@foldkit/ui`) would fail every pair but the default, which alone installs * the adapters. */ const EXAMPLES = ['fields', 'remote', 'tree', 'todo', 'drawer', 'mixins', 'form'].map(name => ({ dir: `examples/${name}/src`, name, })) /** `foldkit-[/sub]` as an app on the meta package imports it, or a failure naming the gap. */ const metaImport = (plusExports, specifier) => { const [name, ...rest] = specifier.split('/') const subpath = ['.', name.slice('foldkit-'.length), ...rest].join('/') if (!Object.hasOwn(plusExports, subpath)) fail(`an example imports ${specifier}, which foldkit-plus does not offer as ${subpath}`) return `foldkit-plus${subpath.slice(1)}` } const copyExamples = plusExports => { for (const example of EXAMPLES) { const into = join(app, 'src', 'examples', example.name) for (const entry of readdirSync(join(root, example.dir), { recursive: true, withFileTypes: true, })) { if (!entry.isFile() || !entry.name.endsWith('.ts')) continue const from = join(entry.parentPath, entry.name) const to = join(into, from.slice(join(root, example.dir).length)) mkdirSync(join(to, '..'), { recursive: true }) writeFileSync( to, readFileSync(from, 'utf8').replace( /(from\s+['"])(foldkit-[a-z-]+(?:\/[a-z-]+)*)(['"])/g, (_, open, specifier, close) => `${open}${metaImport(plusExports, specifier)}${close}`, ), ) } } } /** The scaffold's lint configs, told to skip the examples' demo harnesses. */ const skipDemos = () => { for (const file of ['.oxlintrc.json', '.oxlintrc.effect.json']) { const path = join(app, file) const config = JSON.parse(readFileSync(path, 'utf8')) config.ignorePatterns = [...(config.ignorePatterns ?? []), 'src/examples/**/demo.ts'] writeFileSync(path, JSON.stringify(config, null, 2)) } } /** 4. The scaffold's own checks, over what it drew, every entry point of ours, and the examples. */ const checkScaffold = () => { const plus = JSON.parse( readFileSync(join(app, 'node_modules', 'foldkit-plus', 'package.json'), 'utf8'), ) const entries = Object.keys(plus.exports).map(subpath => subpath === '.' ? 'foldkit-plus' : `foldkit-plus${subpath.slice(1)}`, ) writeFileSync( join(app, 'src', 'foldkitPlus.ts'), entries .map( (entry, i) => `import type * as M${i} from '${entry}'\nexport type Entry${i} = typeof M${i}\n`, ) .join(''), ) const check = (script, over) => { const checked = run(`${manager} run ${script}`, app) if (checked.status !== 0) fail(`${manager} run ${script} fails in the scaffold:\n${checked.output}`) console.log(`published-setup: ${manager} run ${script}, over ${over}`) } copyExamples(plus.exports) skipDemos() check('lint', `${entries.length} entry points and ${EXAMPLES.length} examples`) check('typecheck', `${entries.length} entry points and ${EXAMPLES.length} examples`) } // 3. The guide's npm steps. const npmSteps = () => { const guide = setup(app) const install = guide.split('\n## 3.')[0].split('\n## 2. Install\n')[1] if (install === undefined) fail('the guide has no install step') const fields = /```json\n([\s\S]*?)\n```/.exec(install) const commands = [ ...install.matchAll(/^(npm install [^`\n]+)$/gm), ...(full ? install.matchAll(/`(npm install foldkit-[^`]+)`/g) : []), ].map(match => match[1]) if (commands.length < (full ? 2 : 1)) fail(`the install step names too few npm commands:\n${install}`) const manifestPath = join(app, 'package.json') const readManifest = () => JSON.parse(readFileSync(manifestPath, 'utf8')) // Merged a field at a time, as told: the block's `dependencies` join the // project's rather than replace them. if (fields !== null) { const manifest = readManifest() for (const [field, value] of Object.entries(JSON.parse(fields[1]))) manifest[field] = { ...manifest[field], ...value } writeFileSync(manifestPath, JSON.stringify(manifest, null, 2)) } const ownOverrides = readManifest().overrides ?? {} const direct = new Set() for (const command of commands) { const words = command.split(' ') for (const word of words) if (tarballs.has(word)) direct.add(word) // npm refuses an override of a direct dependency, so ours that are, or // become so here, are installed by tarball instead. const manifest = readManifest() manifest.overrides = { ...ownOverrides, ...Object.fromEntries( [...tarballs] .filter(([name]) => !direct.has(name)) .map(([name, file]) => [name, `file:${file}`]), ), } writeFileSync(manifestPath, JSON.stringify(manifest, null, 2)) const local = words .map(word => (tarballs.has(word) ? `"file:${tarballs.get(word)}"` : word)) .join(' ') const installed = run(local, app) if (installed.status !== 0 || installed.output.includes('ERESOLVE')) fail(`${command} failed (exit ${installed.status}):\n${installed.output}`) // Only what Effect, Foldkit and ours meet counts: a library an adapter brings // may leave an unrelated optional peer of its own unmet (i18next's TypeScript). const listed = JSON.parse(run('npm ls --all --json', app).stdout) const problems = (listed.problems ?? []).filter(problem => /^\w+: (?:effect|@effect\/[^@\s]+|foldkit[^@\s]*|@foldkit\/[^@\s]+)@/.test(problem), ) if (problems.length > 0) fail(`npm ls refuses the tree after ${command}:\n${problems.join('\n')}`) const versions = new Map() const walk = node => { for (const [name, child] of Object.entries(node.dependencies ?? {})) { if (name === 'effect' || name === 'foldkit') versions.set(name, new Set([...(versions.get(name) ?? []), child.version])) walk(child) } } walk(listed) for (const [name, found] of versions) if (found.size !== 1) fail(`after ${command} the tree holds ${name} ${[...found].join(', ')}`) console.log(`published-setup: ${command}`) } console.log(`published-setup: npm runs every step setup prints, for an ${rendering} scaffold`) } // pnpm reads `overrides` and `peerDependencyRules` only at a workspace's root // (#280), which is `top`: the project itself, unless a workspace holds it. const pnpmSteps = (name, project, top, adapters) => { const step = setup(project, pnpmAgent).split('\n## 3.')[0].split('\n## 2. Install\n')[1] ?? '' const into = /first merge this into `([^`]+)`/.exec(step)?.[1] const block = /```(json|yaml)\n([\s\S]*?)\n```/.exec(step) if (into === undefined || block === null) fail(`${name}: the guide gives pnpm no pins:\n${step}`) const target = join(project, into) const read = [join(top, 'package.json'), join(top, 'pnpm-workspace.yaml')] if (!read.includes(target)) fail(`${name}: the guide pins in ${target}, not at the root ${top}`) const commands = [ /^(pnpm add [^`\n]+)$/m.exec(step)?.[1], ...(adapters ? [/`(pnpm add foldkit-auth [^`]+)`/.exec(step)?.[1]] : []), ] if (commands.includes(undefined)) fail(`${name}: the guide names no pnpm install line`) const direct = new Set(commands.flatMap(command => command.split(' '))) const ours = [...tarballs].filter(([each]) => !direct.has(each)) if (block[1] === 'yaml') { const tarballLines = ours.map(([each, file]) => ` ${each}: 'file:${file}'`) const merged = block[2].replace('overrides:\n', `overrides:\n${tarballLines.join('\n')}\n`) writeFileSync(target, `${readFileSync(target, 'utf8')}${merged}\n`) } else { const manifest = JSON.parse(readFileSync(target, 'utf8')) const { pnpm } = JSON.parse(block[2]) pnpm.overrides = { ...pnpm.overrides, ...Object.fromEntries(ours.map(([each, file]) => [each, `file:${file}`])), } writeFileSync(target, JSON.stringify({ ...manifest, pnpm }, null, 2)) } // pnpm's overrides do not reach a peer it installs itself, so a package of // ours that another peers on would come from the registry, at an unreleased // version's number, with that release's peers. Named here, the peer is the // tarball, as it will be once released. const peered = new Set( readdirSync(join(root, 'packages')) .map(dir => join(root, 'packages', dir, 'package.json')) .filter(manifest => existsSync(manifest)) .flatMap(manifest => Object.keys(JSON.parse(readFileSync(manifest, 'utf8')).peerDependencies ?? {}), ), ) const own = join(project, 'package.json') const manifest = JSON.parse(readFileSync(own, 'utf8')) manifest.dependencies = { ...manifest.dependencies, ...Object.fromEntries( ours.filter(([each]) => peered.has(each)).map(([each, file]) => [each, `file:${file}`]), ), } writeFileSync(own, JSON.stringify(manifest, null, 2)) for (const command of commands) { const local = command .split(' ') .map(word => (tarballs.has(word) ? `"file:${tarballs.get(word)}"` : word)) .join(' ') const installed = run(local, project) if (installed.status !== 0) fail(`${name}: ${command} failed:\n${installed.output}`) // pnpm names an unmet peer and installs anyway, so its words are the verdict. const unmet = installed.output .split('\n') .filter(line => /unmet peer (?:effect|@effect\/|foldkit|@foldkit\/)/.test(line)) if (unmet.length > 0) fail(`${name}: ${command} left peers unmet:\n${unmet.join('\n')}`) // The lockfile, not `node_modules/.pnpm`, which keeps what the scaffold's // own install resolved after the pins moved past it. const lock = readFileSync(join(top, 'pnpm-lock.yaml'), 'utf8') for (const each of ['effect', 'foldkit']) { const versions = new Set( [...lock.matchAll(new RegExp(`^ '?${each}@(\\d[^(:'\\s]*)`, 'gm'))].map(found => found[1]), ) if (versions.size !== 1) fail(`${name}: after ${command} pnpm holds ${each} ${[...versions].join(', ')}`) } console.log(`published-setup: ${name}: ${command}`) } } if (manager === 'npm') npmSteps() else pnpmSteps('pnpm-scaffold', app, app, false) checkScaffold() // 5. pnpm's steps over a stand-in: a standalone project, and a workspace member. const pnpmCase = (name, workspace) => { const top = join(home, name) const project = join(top, 'app') mkdirSync(project, { recursive: true }) if (workspace) { writeFileSync(join(top, 'package.json'), JSON.stringify({ name: 'top', private: true })) writeFileSync(join(top, 'pnpm-workspace.yaml'), 'packages:\n - app\n') } // The Effect packages an ssr scaffold names, at the release Foldkit names. writeFileSync( join(project, 'package.json'), JSON.stringify({ name: 'app', private: true, dependencies: { effect: '4.1.0', '@effect/platform-browser': '4.1.0', '@effect/platform-node': '4.1.0', foldkit: '0.170.0', }, }), ) pnpmSteps(name, project, workspace ? top : project, true) } if (full) { pnpmCase('pnpm-standalone', false) pnpmCase('pnpm-workspace', true) console.log('published-setup: pnpm runs them too, in a standalone project and a workspace member') } rmSync(work, { recursive: true, force: true })