GitHub mirror: iterate/kernel takes this repo's main and publishes core/lib to npm as iterate (#23)
jonas, 2026-11-27 14:08 UTC · 2146c017db8e0ffeed5c242e65a2689064b7389a · parent 291a0a8
6 files changed
- A .github/npm-publish.mjs
- A .github/npm-publish.test.mjs
- A .github/workflows/mirror.yml
- A .github/workflows/npm-publish.yml
- M README.md
- M core/lib/package.json
A .github/npm-publish.mjs
@@ -0,0 +1,535 @@ +// npm-publish.mjs — THE `iterate` PACKAGE ON NPM, FROM THIS REPOSITORY. `core/lib` is the package. +// The jobs of .github/workflows/npm-publish.yml are this file's four commands: +// +// node .github/npm-publish.mjs pack --dist-tag main --out out +// node .github/npm-publish.mjs install --tarball out/iterate-<version>.tgz +// node .github/npm-publish.mjs publish --tarball out/iterate-<version>.tgz --dist-tag main +// node .github/npm-publish.mjs check +// +// `pack` packs `core/lib` of this checkout as pnpm packs it (its `prepack` builds it; `catalog:` +// and `workspace:` become versions, and publishConfig applies). The manifest gets the version +// (`versionAt`) and `gitHead` and loses `devDependencies`, which no consumer installs. It is the +// only command that runs the package's code, and its job has no token of npm's. `install` installs +// that tarball where nothing of ours is. `publish` hands npm the same file, with no script of it +// run. A package whose files equal those of the version that its dist-tag names now is not +// published again. Under `main`, `latest` then names what `main` names: it is what npmjs.com shows +// and what `npx iterate` gets. +// +// The job that publishes authenticates by npm's trusted publishing (the job's OIDC token; npm +// 11.5.1 or later): the package's settings on npmjs.com name github.com/iterate/kernel, the +// workflow's file and the environment `npm`. `check` says what the package still lacks there. By +// hand, `npm login` first. +// +// No dependency: the job that holds npm's token runs this file, Node and npm, and nothing else. +import { execFileSync } from "node:child_process"; +import { + appendFileSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, resolve } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; + +/** The package, and its folder in this repository. */ +const NAME = "iterate"; +const FOLDER = "core/lib"; + +/** What `install` runs once the package is installed: the CLI starts, and finds a command. */ +const SMOKE = [ + ["iterate", "--version"], + ["iterate", "git", "setup", "--help"], +]; + +/** This repository's root: this file is in `.github`. */ +const ROOT = fileURLToPath(new URL("..", import.meta.url)); + +/** The workflow's file: what a package's trusted publisher on npmjs.com names. */ +const WORKFLOW = "npm-publish.yml"; + +const DIST_TAGS = ["main", "canary"]; + +/** + * The npm version of a package at a commit: `<package.json version>-<dist-tag>.<committer date>-<sha>`, + * such as `0.1.0-main.20261002T164000Z-3202ce3`. The date is the commit's own, to the second, never + * the clock's, so the version is the same whenever it is worked out. The sha is its first seven + * digits, to tell the commit by eye; the manifest's `gitHead` holds all forty. semver compares a + * prerelease identifier as ASCII text, and the fixed-width date leads it, so a later commit's + * version sorts higher. + */ +export function versionAt({ version, distTag, committedAt, sha }) { + const stamp = new Date(committedAt).toISOString().slice(0, 19).replace(/\W/g, ""); + return `${version}-${distTag}.${stamp}Z-${sha.slice(0, 7)}`; +} + +/** Whether a consumer would get anything new from `packed` over `published`, two packages as + * their files (path to bytes): their files differ, or their manifests do in more than `version` + * and `gitHead`, which name the build and not what it holds, and `devDependencies`. A dependency + * map's order is no difference: pnpm writes the ones it resolves in whichever order they settle. */ +export function differs(packed, published) { + const content = (files) => + [...files] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([path, bytes]) => { + if (path !== "package.json") return [path, bytes.toString("base64")]; + const { version: _v, gitHead: _g, devDependencies: _d, ...manifest } = JSON.parse(bytes); + for (const field of ["dependencies", "peerDependencies", "optionalDependencies"]) + if (manifest[field]) + manifest[field] = Object.fromEntries( + Object.entries(manifest[field]).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), + ); + return [path, JSON.stringify(manifest)]; + }); + return JSON.stringify(content(packed)) !== JSON.stringify(content(published)); +} + +/** + * Packs the package at this checkout's commit into the folder `out`, and says what it packed: the + * commit, the version, how it compares with what `distTag` names on npm, and the tarball's file + * count and npm's `integrity` of it. Publishes nothing. + */ +export async function pack({ distTag, out }) { + const name = NAME; + const folder = FOLDER; + const work = mkdtempSync(join(tmpdir(), "npm-publish-")); + try { + const checkout = ROOT; + const git = (...args) => execFileSync("git", args, { cwd: checkout, encoding: "utf8" }).trim(); + const sha = git("rev-parse", "HEAD"); + // the version and `gitHead` name the commit, so the package's files must be that commit's + const changed = git("status", "--porcelain", "--", folder); + if (changed) throw new Error(`${folder} differs from ${sha}:\n${changed}`); + const committedAt = git("log", "-1", "--format=%cI", sha); + + // what the pack's build needs, by this repository's lockfile and its pnpm + const run = (cwd, command, ...args) => + execFileSync(command, args, { cwd, stdio: ["ignore", process.stderr, "inherit"] }); + run(checkout, "pnpm", "install", "--frozen-lockfile", "--filter", `${name}...`); + run(join(checkout, folder), "pnpm", "pack", "--pack-destination", join(work, "pnpm")); + const [tarball, ...more] = readdirSync(join(work, "pnpm")); + if (!tarball || more.length) + throw new Error(`pnpm pack of ${folder} wrote ${[tarball, ...more]}`); + unpack(join(work, "pnpm", tarball), join(work, "packed")); + + const manifestPath = join(work, "packed/package/package.json"); + const { devDependencies: _d, ...manifest } = JSON.parse(readFileSync(manifestPath, "utf8")); + if (manifest.name !== name) + throw new Error(`${folder} holds ${manifest.name}, not ${name}`); + const version = versionAt({ version: manifest.version, distTag, committedAt, sha }); + writeFileSync( + manifestPath, + `${JSON.stringify({ ...manifest, version, gitHead: sha }, null, 2)}\n`, + ); + + mkdirSync(out, { recursive: true }); + const [packed] = JSON.parse( + execFileSync( + "npm", + [ + "pack", + join(work, "packed/package"), + "--pack-destination", + out, + "--ignore-scripts", + "--json", + ], + { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }, + ), + ); + const last = await publishedAt(name, distTag, work); + const compared = !last + ? `npm has no \`${distTag}\` of it` + : differs(filesOf(join(work, "packed/package")), last.files) + ? `differs from ${last.version}` + : `the same files as ${last.version}: a publish would skip it`; + await say( + [ + `${name}@${version}`, + `- source: ${folder} at ${sha}`, + `- tarball: ${packed.filename}, ${packed.entryCount} files, ${packed.integrity}`, + `- npm \`${distTag}\`: ${compared}`, + ].join("\n"), + ); + } finally { + rmSync(work, { recursive: true, force: true }); + } +} + +/** Installs `tarball` in an empty folder, with its dependencies from npm, and runs SMOKE there. */ +export function install({ tarball }) { + const work = mkdtempSync(join(tmpdir(), "npm-publish-install-")); + try { + unpack(resolve(tarball), work); + const { name } = JSON.parse(readFileSync(join(work, "package/package.json"), "utf8")); + if (name !== NAME) throw new Error(`${tarball} holds ${name}, not ${NAME}`); + const at = join(work, "install"); + mkdirSync(at); + writeFileSync(join(at, "package.json"), "{}\n"); + const run = (command, ...args) => { + console.log(`$ ${[command, ...args].join(" ")}`); + execFileSync(command, args, { cwd: at, stdio: "inherit" }); + }; + run("npm", "install", resolve(tarball)); + for (const command of SMOKE) run("npx", "--no-install", ...command); + } finally { + rmSync(work, { recursive: true, force: true }); + } +} + +/** + * Publishes one tarball that `pack` made, as it is, under `distTag`, and waits until npm serves + * it; under `main`, `latest` then names what `main` names. No script of the package runs. Nothing + * is published when the tarball's files equal those of the version that `distTag` names now, or + * when npm has the version already, so a second run only moves the tags it can. + */ +export async function publish({ tarball, distTag, dryRun }) { + const work = mkdtempSync(join(tmpdir(), "npm-publish-publish-")); + try { + unpack(resolve(tarball), join(work, "packed")); + const { name, version } = JSON.parse( + readFileSync(join(work, "packed/package/package.json"), "utf8"), + ); + if (name !== NAME) throw new Error(`${tarball} holds ${name}, not ${NAME}`); + if (!version.includes(`-${distTag}.`)) + throw new Error(`${name}@${version} was not packed for the dist-tag ${distTag}`); + const npm = await packumentOf(name); + const last = await publishedAt(name, distTag, work); + const unchanged = last && !differs(filesOf(join(work, "packed/package")), last.files); + const has = Boolean(npm?.versions[version]); + const names = unchanged ? last.version : version; + let line = unchanged + ? `${name}: the same files as ${last.version}, not published` + : has + ? `${name}@${version}: npm has it already` + : `${name}@${version}${dryRun ? " (dry run)" : ""}`; + if (!unchanged && !has) { + // npm makes the provenance statement by itself: the job is of a public repository, and the + // manifest's `repository.url` names it. + execFileSync( + "npm", + [ + "publish", + resolve(tarball), + "--tag", + distTag, + "--access", + "public", + "--ignore-scripts", + ...(dryRun ? ["--dry-run"] : []), + ], + { stdio: "inherit" }, + ); + if (!dryRun) await untilNpmServes({ name, distTag, version }); + } + const latest = npm?.["dist-tags"].latest; + let refused = false; + if (distTag === "main" && latest !== names) { + const moved = dryRun ? undefined : await pointLatestAt(name, names); + refused = Boolean(moved); + line += moved + ? `; \`latest\` stays ${latest || "unset"}: ${moved}` + : `; \`latest\` is now ${names}, was ${latest || "unset"}${dryRun ? " (dry run)" : ""}`; + } + await say(`npm \`${distTag}\`: ${line}`); + if (refused) throw new Error(`npm would not move \`latest\` of ${name}`); + } finally { + rmSync(work, { recursive: true, force: true }); + } +} + +/** Fails unless npm is ready for this repository's workflow to publish the package, and says + * what sets it up when it is not (`missingOnNpm`). */ +export async function check() { + const oidc = jobOidc(); + if (!oidc) throw new Error(`check asks npm as a job of ${WORKFLOW}, which this is not`); + const missing = await missingOnNpm(NAME, oidc); + if (!missing) return await say(`npm is ready for this workflow to publish ${NAME}.`); + await say( + [ + `${missing.said}. As someone who may publish it:`, + "", + "```sh", + ...missing.setup, + "```", + ].join("\n"), + ); + throw new Error(`npm is not ready for ${NAME}`); +} + +/** What a package needs on npmjs.com before the workflow can publish it, in the order it gets + * them. */ +const NPM_SETUP = ["package", "trusted publisher", "dist-tag"]; + +/** The tag `missingOnNpm` adds to a package and removes again. Nothing reads it. */ +const CHECK_TAG = "npm-publish-check"; + +/** + * WHAT `name` STILL NEEDS ON NPMJS.COM BEFORE THE WORKFLOW CAN PUBLISH IT: the first of NPM_SETUP + * it lacks, with npm's answer and the commands for it and each step after (`setup`), or undefined + * when it has them all. Asked as a job of the workflow that the package is to trust: + * + * - `package`: npm has no such package, and sets a trusted publisher only on one that exists. + * - `trusted publisher`: npm trades the job no token for the package. + * - `dist-tag`: npm refuses the traded token a tag. npm shows a trusted publisher's permissions to + * no token, so the test is a write: CHECK_TAG, added at the version `latest` names and removed + * again, each with a token of its own. `latest` and `main` are never written. + * + * "Allow npm publish" is not checked: only a publish would show it. + */ +async function missingOnNpm(name, oidc) { + const repository = process.env.GITHUB_REPOSITORY; + const commands = { + package: `cd "$(mktemp -d)" && echo '${JSON.stringify({ name, version: "0.0.0" })}' > package.json && npm publish --access public`, + "trusted publisher": `open https://www.npmjs.com/package/${name}/access && echo 'Add a trusted publisher: GitHub Actions, ${repository}, ${WORKFLOW}, environment npm, "Allow npm publish"'`, + "dist-tag": `open https://www.npmjs.com/package/${name}/access && echo 'On the trusted publisher of ${repository}, tick "Allow npm dist-tag", save'`, + }; + const lacks = (step, said) => ({ + said, + setup: NPM_SETUP.slice(NPM_SETUP.indexOf(step)).map((each) => commands[each]), + }); + const tags = `https://registry.npmjs.org/-/package/${name.replace("/", "%2f")}/dist-tags`; + + const read = await fetchRepeated(tags); + if (!read.ok) + return lacks( + "package", + `${name} is not on npm (npm answered ${read.status}: ${await read.text()})`, + ); + const { latest } = await read.json(); + + const toAdd = await tradedToken(name, oidc); + if (toAdd.refused) + return lacks( + "trusted publisher", + `${name} does not trust this workflow to publish it (${toAdd.refused})`, + ); + // a write is sent once: npm takes its token for one request to this route + const added = await fetch(`${tags}/${CHECK_TAG}`, { + method: "PUT", + headers: { authorization: `Bearer ${toAdd.token}`, "content-type": "application/json" }, + body: JSON.stringify(latest), + }); + if (!added.ok) + return lacks( + "dist-tag", + `${name} does not let this workflow move its dist-tags (npm answered ${added.status}: ${await added.text()})`, + ); + + const toRemove = await tradedToken(name, oidc); + if (toRemove.refused) + throw new Error( + `${name} keeps the tag ${CHECK_TAG}: no token to remove it, ${toRemove.refused}`, + ); + const removed = await fetch(`${tags}/${CHECK_TAG}`, { + method: "DELETE", + headers: { authorization: `Bearer ${toRemove.token}` }, + }); + if (!removed.ok) + throw new Error( + `${name} keeps the tag ${CHECK_TAG}: npm answered its removal ${removed.status}: ${await removed.text()}`, + ); + return undefined; +} + +/** + * Makes `latest` of `name` name `version`; answers npm's reason when npm refuses, else undefined. + * `npm dist-tag add`, as whoever npm is logged in as. In CI that is no one: trusted publishing logs + * in `npm publish` alone. So the same trade is made here (`tradedToken`), and npm is handed the + * token in a config file of its own. npm moves a tag for that token only where the package's + * trusted publisher has "Allow npm dist-tag". + */ +async function pointLatestAt(name, version) { + const config = mkdtempSync(join(tmpdir(), "npm-publish-latest-")); + try { + const oidc = jobOidc(); + const traded = oidc && (await tradedToken(name, oidc)); + if (traded?.refused) return `no token for ${name}: ${traded.refused}`; + if (traded) + writeFileSync(join(config, "npmrc"), `//registry.npmjs.org/:_authToken=${traded.token}\n`); + execFileSync("npm", ["dist-tag", "add", `${name}@${version}`, "latest"], { + stdio: ["inherit", "inherit", "pipe"], + encoding: "utf8", + env: traded ? { ...process.env, NPM_CONFIG_USERCONFIG: join(config, "npmrc") } : process.env, + }); + return undefined; + } catch (error) { + const output = String(error.stderr || error.message); + process.stderr.write(`${output}\n`); + // npm's own sentence when it has one: `npm error 403 403 Forbidden - PUT … - <why>` + return output.match(/^npm error \d{3} (.+)$/m)?.[1] || output.trim().split("\n")[0]; + } finally { + rmSync(config, { recursive: true, force: true }); + } +} + +/** How this job asks GitHub for its OIDC token (a GitHub Actions job with `id-token: write`), or + * undefined anywhere else. */ +function jobOidc() { + const { ACTIONS_ID_TOKEN_REQUEST_URL: url, ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer } = process.env; + return url && bearer ? { url, bearer } : undefined; +} + +/** + * npm's token for `name` in a GitHub Actions job whose workflow the package trusts, as `npm + * publish` gets one (npm/cli lib/utils/oidc.js): the job's OIDC token, for npm's audience, traded + * at the registry. npm takes a token for one request to a route. `refused` is npm's answer when it + * trades none: the same 404, "package not found", for a package that it does not have and for one + * whose trusted publishers do not name the job's workflow. + */ +async function tradedToken(name, oidc) { + const identity = await fetchRepeated(`${oidc.url}&audience=npm:registry.npmjs.org`, { + headers: { authorization: `Bearer ${oidc.bearer}` }, + }); + if (!identity.ok) + throw new Error( + `GET the job's OIDC token answered ${identity.status}: ${await identity.text()}`, + ); + const { value } = await identity.json(); + const traded = await fetchRepeated( + `https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/${name.replace("/", "%2f")}`, + { method: "POST", headers: { authorization: `Bearer ${value}` } }, + ); + if (!traded.ok) return { refused: `npm answered ${traded.status}: ${await traded.text()}` }; + return { token: (await traded.json()).token }; +} + +/** Prints `text`, and adds it to the job's summary in GitHub Actions. */ +async function say(text) { + console.log(text); + if (process.env.GITHUB_STEP_SUMMARY) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n\n`); +} + +/** Extracts `tarball` into the new folder `into`, whose `package/` it fills. */ +function unpack(tarball, into) { + mkdirSync(into, { recursive: true }); + execFileSync("tar", ["-xzf", tarball, "-C", into]); +} + +/** Every file under `folder`, by its path there. */ +function filesOf(folder) { + return new Map( + readdirSync(folder, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => { + const file = join(entry.parentPath, entry.name); + return [relative(folder, file), readFileSync(file)]; + }), + ); +} + +/** How often a read is asked again when the connection fails or the server answers 429 or 5xx. */ +const HTTP_DELAYS_MS = [1_000, 5_000, 15_000]; + +/** `fetch`, asked again after each of `delaysMs` while the connection fails or `again` says so of + * the answer. Only for a request that may be sent twice. */ +async function fetchRepeated(url, init = {}, options = {}) { + const { delaysMs = HTTP_DELAYS_MS, again = (r) => r.status === 429 || r.status >= 500 } = options; + for (let attempt = 0; ; attempt++) { + const last = attempt === delaysMs.length; + try { + const response = await fetch(url, { ...init, signal: AbortSignal.timeout(120_000) }); + if (last || !(await again(response.clone()))) return response; + await response.arrayBuffer().catch(() => undefined); + } catch (error) { + if (last) throw error; + } + await sleep(delaysMs[attempt]); + } +} + +/** What npm has of `name` (its dist-tags, and each version's tarball), or undefined before the + * first publish. `?write=true` asks for the packument uncached, as npm does before it writes one: + * the cached copy lags by up to five minutes. */ +async function packumentOf(name, options) { + const url = `https://registry.npmjs.org/${name.replace("/", "%2f")}?write=true`; + const answer = await fetchRepeated(url, {}, options); + if (answer.status === 404) return undefined; + if (!answer.ok) throw new Error(`GET ${url} answered ${answer.status}`); + return await answer.json(); +} + +/** npm serves a fresh version in its packument minutes before its tarball. A tarball that the + * packument names is asked for again on this schedule, about eight minutes in all. */ +const NPM_PROCESSING_MS = [10_000, 20_000, 30_000, ...Array.from({ length: 6 }, () => 60_000)]; + +/** The version that `distTag` of `name` names on npm, with its files, or undefined when nothing + * has that tag yet. `work` is a folder to unpack in. */ +async function publishedAt(name, distTag, work) { + const npm = await packumentOf(name); + const version = npm?.["dist-tags"][distTag]; + if (!version) return undefined; + const url = npm.versions[version].dist.tarball; + const answer = await fetchRepeated( + url, + {}, + { + delaysMs: NPM_PROCESSING_MS, + again: (r) => r.status === 404 || r.status === 429 || r.status >= 500, + }, + ); + if (!answer.ok) throw new Error(`GET ${url} answered ${answer.status}`); + const into = mkdtempSync(join(work, "published-")); + writeFileSync(join(into, "tarball.tgz"), Buffer.from(await answer.arrayBuffer())); + unpack(join(into, "tarball.tgz"), into); + return { version, files: filesOf(join(into, "package")) }; +} + +/** How long a publish waits for npm to serve its version: about thirteen minutes in all, twice + * the longest wait measured. */ +const NPM_SERVES_MS = [10_000, 20_000, 30_000, ...Array.from({ length: 12 }, () => 60_000)]; + +/** + * Waits until npm's packument names `version` under `distTag`, and throws what the dist-tag still + * names when it never does. `npm publish` returns once npm has taken a version; its packument holds + * it later (100 seconds to six minutes, measured 2026-11-12). Until then the dist-tag names the + * version before, and npm can drop a `latest` move to the new version. + */ +async function untilNpmServes({ name, distTag, version }) { + let names; + await packumentOf(name, { + delaysMs: NPM_SERVES_MS, + again: async (r) => { + if (r.status === 429 || r.status >= 500) return true; + // a 404 is a package's first publish: npm has no packument for it yet + names = r.ok ? (await r.json())["dist-tags"][distTag] : undefined; + return names !== version; + }, + }); + if (names !== version) + throw new Error( + `npm has yet to serve ${name}@${version}: \`${distTag}\` names ${names || "nothing"}`, + ); +} + +// `install` runs on Node 22, which has no `import.meta.main` +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const [command, ...rest] = process.argv.slice(2); + const { values } = parseArgs({ + args: rest, + options: { + "dist-tag": { type: "string", default: "main" }, + out: { type: "string", default: "out" }, + tarball: { type: "string" }, + "dry-run": { type: "boolean", default: false }, + }, + }); + const distTag = values["dist-tag"]; + if (!DIST_TAGS.includes(distTag)) throw new Error(`--dist-tag is one of ${DIST_TAGS.join(", ")}`); + const one = (what, value) => { + if (!value) throw new Error(`${command} needs --${what}`); + return value; + }; + if (command === "pack") await pack({ distTag, out: resolve(values.out) }); + else if (command === "install") install({ tarball: one("tarball", values.tarball) }); + else if (command === "publish") + await publish({ tarball: one("tarball", values.tarball), distTag, dryRun: values["dry-run"] }); + else if (command === "check") await check(); + else throw new Error("usage: node .github/npm-publish.mjs <pack | install | publish | check> …"); +}
A .github/npm-publish.test.mjs
@@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { differs, versionAt } from "./npm-publish.mjs"; + +test("a version names the dist-tag, the commit's date and the commit", () => { + assert.equal( + versionAt({ + version: "0.4.1", + distTag: "main", + committedAt: "2026-11-26T23:22:08+01:00", + sha: "ca5d72a51c4447512af828687fc947a3ae0653f3", + }), + "0.4.1-main.20261126T222208Z-ca5d72a", + ); +}); + +const files = (manifest, more = {}) => + new Map( + Object.entries({ "package.json": JSON.stringify(manifest), ...more }).map(([path, text]) => [ + path, + Buffer.from(text), + ]), + ); + +test("the version, the commit, devDependencies and a dependency map's order are no difference", () => { + assert.equal( + differs( + files( + { name: "a", version: "1", gitHead: "x", dependencies: { b: "1", c: "2" } }, + { "index.js": "1" }, + ), + files( + { + name: "a", + version: "2", + gitHead: "y", + dependencies: { c: "2", b: "1" }, + devDependencies: {}, + }, + { "index.js": "1" }, + ), + ), + false, + ); +}); + +test("a changed file, a new file and a changed dependency are each a difference", () => { + const base = files({ name: "a", dependencies: { b: "1" } }, { "index.js": "1" }); + assert.equal( + differs(base, files({ name: "a", dependencies: { b: "1" } }, { "index.js": "2" })), + true, + ); + assert.equal( + differs( + base, + files({ name: "a", dependencies: { b: "1" } }, { "index.js": "1", "more.js": "" }), + ), + true, + ); + assert.equal( + differs(base, files({ name: "a", dependencies: { b: "2" } }, { "index.js": "1" })), + true, + ); +});
A .github/workflows/mirror.yml
@@ -0,0 +1,46 @@ +name: mirror +# github.com/iterate/kernel is a read-only mirror of https://git.iterate.com/repos/kernel, with the +# same commits. This workflow runs in the mirror: it reads the source's main with no credential and +# pushes it to the mirror's main. The push never forces: when the two have parted, it fails and a +# person looks. +# +# It pushes with the deploy key in the secret MIRROR_DEPLOY_KEY, which can write to this repository +# alone. The job's own token will not do: GitHub lets it push no commit that changes a workflow, and +# starts no workflow for what it pushes. The key's push starts npm-publish.yml. +# +# After a merge to the source, to mirror at once: `gh workflow run mirror.yml --repo iterate/kernel`. +# GitHub stops a schedule in a repository with no commit for 60 days; a dispatch starts it again. +on: + schedule: + - cron: "*/10 * * * *" + workflow_dispatch: +concurrency: + group: mirror + cancel-in-progress: false +permissions: {} +jobs: + mirror: + if: github.repository == 'iterate/kernel' + runs-on: ubuntu-latest + steps: + - name: Push the source's main to this repository's main + env: + MIRROR_DEPLOY_KEY: ${{ secrets.MIRROR_DEPLOY_KEY }} + run: | + install -m 700 -d "$RUNNER_TEMP/ssh" + install -m 600 /dev/null "$RUNNER_TEMP/ssh/key" + printf '%s\n' "$MIRROR_DEPLOY_KEY" > "$RUNNER_TEMP/ssh/key" + # GitHub's host key (https://docs.github.com/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints) + echo "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" > "$RUNNER_TEMP/ssh/known_hosts" + export GIT_SSH_COMMAND="ssh -i $RUNNER_TEMP/ssh/key -o IdentitiesOnly=yes -o UserKnownHostsFile=$RUNNER_TEMP/ssh/known_hosts -o StrictHostKeyChecking=yes" + git init --quiet "$RUNNER_TEMP/kernel" + cd "$RUNNER_TEMP/kernel" + git fetch --quiet https://git.iterate.com/repos/kernel main + source="$(git rev-parse FETCH_HEAD)" + mirror="$(git ls-remote git@github.com:iterate/kernel.git refs/heads/main | cut -f1)" + if [ "$source" = "$mirror" ]; then + echo "main is at $source in both" | tee -a "$GITHUB_STEP_SUMMARY" + exit 0 + fi + git push --quiet git@github.com:iterate/kernel.git "$source:refs/heads/main" + echo "main: ${mirror:-nothing} to $source" | tee -a "$GITHUB_STEP_SUMMARY"
A .github/workflows/npm-publish.yml
@@ -0,0 +1,129 @@ +name: npm +# Publishes `core/lib` of this repository to npm as `iterate`, the SDK and the CLI +# (.github/npm-publish.mjs says how). It runs in the mirror github.com/iterate/kernel: npm's trusted +# publishing takes an OIDC token from GitHub's own runners alone. The package's settings on +# npmjs.com name that repository, this file and the environment `npm`. +# +# A push to main packs the package and installs it, and publishes nothing. A dispatch on main names +# what to do with main's tip: +# +# gh workflow run npm-publish.yml --repo iterate/kernel -f action=<dry-run | canary | main | check> +# +# `pack` is the only job that runs the package's code, and it has no OIDC token. `install` installs +# its tarball on computers that have nothing of ours. `publish` hands npm the tarball that both +# installs passed, with no script of it run. `check` asks npm, as this workflow, whether the +# package trusts it; it writes and removes the tag `npm-publish-check` and nothing else. +on: + push: + branches: + - main + workflow_dispatch: + inputs: + action: + description: "`dry-run` packs and installs, and publishes nothing. `canary` publishes and leaves `latest` alone. `main` publishes and moves `latest`. `check` asks npm whether the package trusts this workflow." + type: choice + options: + - dry-run + - canary + - main + - check + default: dry-run +# One run at a time for an action, in order, and no run is cancelled: a publish that was cut off +# could leave `latest` behind `main`. +concurrency: + group: npm-${{ inputs.action || 'push' }} + cancel-in-progress: false +permissions: {} +jobs: + pack: + if: github.repository == 'iterate/kernel' && inputs.action != 'check' + runs-on: ubuntu-latest + permissions: + contents: read + steps: + # no token of this repository stays on disk: the pack runs the package's own build + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version-file: .nvmrc + # npm 11 packs the tarball; pnpm is the version that package.json names + - run: npm install --global npm@11 pnpm@12.18.0 + - run: node --test .github/ + # the version names the dist-tag, so the pack takes it; a dry run packs for `main` + - run: node .github/npm-publish.mjs pack --dist-tag "$DIST_TAG" --out "$RUNNER_TEMP/tarball" + env: + DIST_TAG: ${{ inputs.action == 'canary' && 'canary' || 'main' }} + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: tarball + path: ${{ runner.temp }}/tarball/*.tgz + if-no-files-found: error + # A computer with nothing of ours installs the tarball: Node at the oldest version that the + # package allows, its dependencies from npm, and of this repository the script alone. + install: + needs: pack + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + sparse-checkout: .github + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 22 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: tarball + path: ${{ runner.temp }}/tarball + - run: node .github/npm-publish.mjs install --tarball "$(ls "$RUNNER_TEMP"/tarball/*.tgz)" + # npm gets the tarball that both installs passed, as it is: no script of the package runs here. + # Only a dispatch on main that names a dist-tag gets here. The environment `npm` takes main alone. + publish: + needs: [pack, install] + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.action == 'canary' || inputs.action == 'main') + runs-on: ubuntu-latest + environment: npm + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + sparse-checkout: .github + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 26 + # trusted publishing needs npm 11.5.1 or later + - run: npm install --global npm@11 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: tarball + path: ${{ runner.temp }}/tarball + - run: node .github/npm-publish.mjs publish --tarball "$(ls "$RUNNER_TEMP"/tarball/*.tgz)" --dist-tag "$DIST_TAG" + env: + DIST_TAG: ${{ inputs.action }} + check: + if: github.repository == 'iterate/kernel' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.action == 'check' + runs-on: ubuntu-latest + environment: npm + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + sparse-checkout: .github + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 26 + - run: node .github/npm-publish.mjs check
M README.md
@@ -1,4 +1,4 @@ -# iterate/core +# iterate/kernel The platform behind [iterate](https://iterate.com). A **mind** is one deployment: a small stack of Cloudflare Workers in its owner's own Cloudflare account, at its own domain. It holds agents, their memory as event logs, git repos, secrets and the apps its owner writes. Its people are members, who reach all of it, and anyone else, who reaches only what its apps serve. @@ -36,9 +36,7 @@ AGPL-3.0 ([LICENSE](LICENSE)), except the SDK (`core/lib`, npm `iterate`) and the templates (`core/configs`), which are Apache-2.0 by the LICENSE in each folder. -This repo is a read-only copy of `core/` from iterate's own repo, made by [Copybara](https://github.com/google/copybara) after each change to it. Paths are the same in both, and each commit ends in `GitOrigin-RevId: <sha>`, naming the commit it came from. A comment here may name a file outside `core/` (`docs/`, `tasks/`, `lint/`, `packages/`): that file is in iterate's own repo, or in iterate/packages. +The source is `https://git.iterate.com/repos/kernel`. [github.com/iterate/kernel](https://github.com/iterate/kernel) is a read-only mirror of it, with the same commits: [`.github/workflows/mirror.yml`](.github/workflows/mirror.yml) pushes the source's main there. The mirror publishes `core/lib` to npm as `iterate` ([`.github/workflows/npm-publish.yml`](.github/workflows/npm-publish.yml)). -- Found a bug, or want something? [Open an issue](https://github.com/iterate/core/issues). -- Have a fix in mind? Push it to a fork and link the compare view in an issue. Pull requests are turned off here: the next copy would overwrite them. - -This README lives in iterate's repo at `copybara/core/README.md`. +- Found a bug, or want something? [Open an issue](https://github.com/iterate/kernel/issues). +- Have a fix in mind? Push it to a fork and link the compare view in an issue. A pull request on the mirror cannot be merged: the mirror takes the source's commits alone.
M core/lib/package.json
@@ -6,12 +6,12 @@ "type": "module", "repository": { "type": "git", - "url": "git+https://github.com/iterate/core", + "url": "git+https://github.com/iterate/kernel.git", "directory": "core/lib" }, - "homepage": "https://github.com/iterate/core#readme", + "homepage": "https://github.com/iterate/kernel/tree/main/core/lib#readme", "bugs": { - "url": "https://github.com/iterate/core/issues" + "url": "https://github.com/iterate/kernel/issues" }, "keywords": [ "iterate",