Skip to content

Commit e4e8b4c

Browse files
authored
fix(library): gate findings on the packaging PR (#156)
1 parent f721bb1 commit e4e8b4c

8 files changed

Lines changed: 340 additions & 83 deletions

File tree

‎.github/scripts/package-smoke.ts‎

Lines changed: 46 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,45 @@
77
* type the emitter could not name, fails here instead of on a consumer's
88
* machine.
99
*
10-
* Usage: `bun .github/scripts/package-smoke.ts` from anywhere; every temp
10+
* Usage: `bun .github/scripts/package-smoke.ts` from anywhere; the temp
1111
* directory is removed on every path, failure included.
1212
*/
1313

1414
import { execFileSync } from "node:child_process";
15-
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
15+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
1616
import { tmpdir } from "node:os";
1717
import { join } from "node:path";
18+
import { SECTION_KEYS } from "../../src/schema.js";
1819

1920
/** This script lives at .github/scripts/, two levels below the repository root. */
2021
const REPO_ROOT = join(import.meta.dir, "..", "..");
2122

2223
const PACKAGE = "@vivswan/github-settings-as-code";
2324

24-
/** The consumer's runtime import: the entry names and the schema subpath, each asserted. */
25-
const NODE_CONSUMER = `import { SECTION_KEYS, validateSettings } from "${PACKAGE}";
25+
/**
26+
* The node that runs the consumer. The build tooling (tsdown) needs a newer
27+
* node than the engines floor package.json advertises, so CI builds on the
28+
* PATH node and names the floor's binary here for the consumer alone.
29+
*/
30+
const CONSUMER_NODE = process.env.SMOKE_CONSUMER_NODE ?? "node";
31+
32+
/** The `$id` the committed schema publishes; the schema subpath must serve that document. */
33+
const SCHEMA_ID =
34+
"https://raw.githubusercontent.com/Vivswan/github-settings-as-code/HEAD/lib/settings.schema.json";
35+
36+
/**
37+
* The consumer's runtime import. The section list and the schema id are
38+
* pinned from this checkout's source, so the tarball's bundle must expose
39+
* exactly what src/ declares, not merely something.
40+
*/
41+
const NODE_CONSUMER = `import { deepStrictEqual } from "node:assert/strict";
42+
import { SECTION_KEYS, validateSettings } from "${PACKAGE}";
2643
import schema from "${PACKAGE}/settings.schema.json" with { type: "json" };
2744
const result = validateSettings({ labels: [] });
2845
if (result.isErr()) throw new Error("validateSettings rejected an empty labels list: " + result.error.code);
29-
if (!SECTION_KEYS.includes("labels")) throw new Error("SECTION_KEYS lacks labels");
30-
if (typeof schema.$schema !== "string") throw new Error("the schema subpath did not resolve to the JSON Schema");
46+
deepStrictEqual(result.value, { settings: { labels: [] }, warnings: [] });
47+
deepStrictEqual([...SECTION_KEYS], ${JSON.stringify(SECTION_KEYS)});
48+
deepStrictEqual(schema.$id, ${JSON.stringify(SCHEMA_ID)});
3149
console.log("imported " + SECTION_KEYS.length + " section keys and the schema");
3250
`;
3351

@@ -54,26 +72,23 @@ function capture(command: string, args: string[], cwd: string): string {
5472
});
5573
}
5674

57-
/**
58-
* Give `body` fresh temp directories under `prefix` and remove every one of
59-
* them when it returns or throws.
60-
*/
61-
export async function withTempDirs<T>(
75+
export interface SmokeDirs {
76+
readonly pack: string;
77+
readonly consumer: string;
78+
}
79+
80+
export async function withSmokeDirs<T>(
6281
prefix: string,
63-
count: number,
64-
body: (dirs: string[]) => Promise<T> | T,
82+
body: (dirs: SmokeDirs) => Promise<T> | T,
6583
): Promise<T> {
66-
// Allocated inside the try, so a failing second mkdtemp still removes the first.
67-
const dirs: string[] = [];
84+
const root = mkdtempSync(join(tmpdir(), prefix));
6885
try {
69-
for (let i = 0; i < count; i++) {
70-
dirs.push(mkdtempSync(join(tmpdir(), prefix)));
71-
}
86+
const dirs: SmokeDirs = { pack: join(root, "pack"), consumer: join(root, "consumer") };
87+
mkdirSync(dirs.pack);
88+
mkdirSync(dirs.consumer);
7289
return await body(dirs);
7390
} finally {
74-
for (const dir of dirs) {
75-
rmSync(dir, { recursive: true, force: true });
76-
}
91+
rmSync(root, { recursive: true, force: true });
7792
}
7893
}
7994

@@ -96,27 +111,21 @@ export function packedTarball(packJson: string, destination: string): string {
96111
async function main(): Promise<void> {
97112
run("bun", ["run", "build:lib"], REPO_ROOT);
98113
run("bun", ["run", "lint:package"], REPO_ROOT);
99-
await withTempDirs("gsac-smoke-", 2, ([packDir, consumerDir]) => {
100-
if (packDir === undefined || consumerDir === undefined) {
101-
throw new Error("withTempDirs handed out fewer directories than asked");
102-
}
114+
await withSmokeDirs("gsac-smoke-", ({ pack, consumer }) => {
103115
// --ignore-scripts keeps the prepare hook's output out of the JSON stdout.
104116
const tarball = packedTarball(
105-
capture(
106-
"npm",
107-
["pack", "--json", "--ignore-scripts", "--pack-destination", packDir],
108-
REPO_ROOT,
109-
),
110-
packDir,
117+
capture("npm", ["pack", "--json", "--ignore-scripts", "--pack-destination", pack], REPO_ROOT),
118+
pack,
111119
);
112120
writeFileSync(
113-
join(consumerDir, "package.json"),
121+
join(consumer, "package.json"),
114122
`${JSON.stringify({ name: "smoke-consumer", private: true, type: "module" }, null, 2)}\n`,
115123
);
116-
run("npm", ["install", tarball, "--no-audit", "--no-fund"], consumerDir);
117-
writeFileSync(join(consumerDir, "main.mjs"), NODE_CONSUMER);
118-
run("node", ["main.mjs"], consumerDir);
119-
writeFileSync(join(consumerDir, "main.ts"), TS_CONSUMER);
124+
run("npm", ["install", tarball, "--no-audit", "--no-fund"], consumer);
125+
writeFileSync(join(consumer, "main.mjs"), NODE_CONSUMER);
126+
run(CONSUMER_NODE, ["--version"], consumer);
127+
run(CONSUMER_NODE, ["main.mjs"], consumer);
128+
writeFileSync(join(consumer, "main.ts"), TS_CONSUMER);
120129
run(
121130
join(REPO_ROOT, "node_modules", ".bin", "tsc"),
122131
[
@@ -132,7 +141,7 @@ async function main(): Promise<void> {
132141
"es2022",
133142
"main.ts",
134143
],
135-
consumerDir,
144+
consumer,
136145
);
137146
});
138147
console.log("package smoke: ok");

‎.github/workflows/checks.yml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,24 @@ jobs:
8080

8181
# The packed tarball is imported from a fresh consumer project under Node and under tsc with skipLibCheck off, so a
8282
# declaration leaking a devDependency type fails here, not on a consumer's machine.
83+
# The consumer runs on the engines floor package.json advertises and on current node; tsdown needs a newer node
84+
# than the floor, so the PATH node is 24 and the floor's binary is handed to the consumer alone.
8385
package-smoke:
8486
runs-on: ubuntu-latest
87+
strategy:
88+
fail-fast: false
89+
matrix:
90+
node-version: ["22.14", "24"]
8591
steps:
8692
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
8793
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
8894
with:
8995
bun-version-file: .bun-version
96+
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
97+
with:
98+
node-version: ${{ matrix.node-version }}
99+
- name: Hand the consumer its node
100+
run: echo "SMOKE_CONSUMER_NODE=$(command -v node)" >> "$GITHUB_ENV"
90101
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
91102
with:
92103
node-version: 24

‎.gitignore‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,6 @@ dist
404404
# Finder metadata, kept ignored even if the managed macOS block above changes.
405405
.DS_Store
406406

407-
# The library build (bun run build:lib, tsdown) is built, not committed, like
408-
# lib/index.js above; the packaged branch and npm carry it.
407+
# The library build (bun run build:lib) is built, never committed, like
408+
# lib/index.js above; the npm tarball ships it.
409409
lib/pkg/

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ GitHub Settings as Code: GitHub Action applying declarative repository settings:
3535
<!-- END REPO-PLATFORM MANAGED -->
3636

3737
- `lib/settings.schema.json` is the COMMITTED JSON Schema for settings.yml, generated from the zod slices in `src/sections/<key>/schema.ts` as composed into the settings document by `src/schema.ts`. Each slice is ONE declaration that produces its config type (z.infer), the section's tolerant runtime shape (the section module derives `loosen(<slice>)` itself; the factory-minted families - secrets, variables, the two setup sections, and the list sections on `listSection` - get it from their shared factory in `src/sections/shared/`, which does that derivation once), and its part of the published schema (`.meta({id})` names its definitions; the descriptions come from the `schema:` map in the section's `<key>.docs.yml`, keyed `Definition.field`, which the generator attaches and fails on when a site or a key is unmatched); `src/schema.ts` adds only the document-level wrappers and pins each property to its slice with a lockstep type. Regenerate the schema with `bun run build:schema` after a schema-affecting `src/` change - CI's schema-check job fails when it drifts. `lib/index.js`, the bundled entrypoint the action runs (node24), is NOT committed on main: every workflow that executes the action builds it first (`bun run build:bundle`), the e2e runner builds it to a temp path, and a release builds and commits it on a packaged child of the release commit, which is what every `vX.Y.Z` tag and the moving major point at (main itself stays source-only). `lib/` is exempt from the typography check (third-party unicode in the bundle; the schema descriptions are checked at source) and excluded from [biome](https://biomejs.dev).
38-
- `lib/pkg/` is the npm library build: `bun run build:lib` (tsdown, configured in `tsdown.config.ts`) bundles `src/index.ts` into one ESM `index.js` plus one `index.d.ts` with the runtime dependencies external; like `lib/index.js` it is built, never committed. `package.json` publishes it as `@vivswan/github-settings-as-code` through its `exports` map (`.` to the build, `./settings.schema.json` to the committed schema, `./package.json` to itself; `files` ships only those plus LICENSE.md and README.md), and `test/package-json.test.ts` pins the manifest's field set and holds its `version` equal to `.release-please-manifest.json` (release-please's json extra-file rewrites it). The package-smoke job in `checks.yml` (`bun .github/scripts/package-smoke.ts`) builds the library, runs publint and attw, installs the packed tarball into a fresh consumer, and imports it under Node and under tsc with skipLibCheck off, so a declaration that leaks a devDependency type or a type the emitter cannot name fails there; a type a section module exposes must therefore be exported from its home module. The library reference is docs/reference/library.md.
38+
- The npm library (`@vivswan/github-settings-as-code`, built into `lib/pkg/` by `bun run build:lib`, never committed) is described in docs/reference/library.md. One rule the tooling cannot infer: a type a section module exposes must be exported from its home module, or the bundled declarations cannot reach it and the package-smoke job fails.
3939
- The import layering of `src/` is declared in `architecture.yml` and enforced by `bun run lint:arch`, so a new cross-layer import is a deliberate edit to that file; the module map in `docs/reference/architecture.md` is generated from it.
4040
- The apply/check engine layout: `src/main.ts` is the thin bundled entrypoint; `src/index.ts` is the public entry (declaration-only re-exports, pinned by test/library/public-surface.test.ts); `src/action/` is the GitHub Actions layer and a CONSUMER of that entry: its only import outside itself is `../index.js`, the one edge `architecture.yml` grants it; `src/flows/` holds the run flows the action and a library caller share (single, multi, merge, delivery, redaction); `src/io.ts` is the import-free Io output port; `src/types.ts` holds the leaf type vocabulary; `src/engine/` is the per-repo pipeline (orchestrate, validate, merge, diff, secret references); `src/github/` is the REST client, pagination, and repo-file fetch; `src/discovery/` resolves multi-repo targets; `src/report/` composes and delivers the private report. Under `src/sections/`, each settings section is one self-contained DIRECTORY `src/sections/<key>/`: `index.ts` (the `SectionModule` - key, PAT grant advice, the loose shape derived from the slice, handler), `schema.ts` (the zod slice), `mock.ts` (the e2e mock fragment), `generators.ts` (the fuzz fragment; the secret and variable factory families share theirs in `test/e2e/generators.ts` instead), `<key>.test.ts` (absent where a shared factory's suite under `test/sections/` covers the section), and `scenarios/`. Beside the section directories sit `contract/` (the layered section contract: permissions/endpoints/graphql/module/errors/requests/live), `shared/` (the cross-section engines and factories, plus the schema helpers), and `registry.ts` (the single registration point). All GitHub API list calls must go through `listAll()` (bare-array endpoints) or `listAllEnveloped()` (endpoints that wrap the list in a `{total_count, <key>: []}` envelope), both backed by the single page loop in `src/github/paginate.ts`; errors through `call()`/`throwFor()` so the permission policy (`on-missing-permission`, `required-sections`) works.
4141
- Adding a section: create `src/sections/<key>/` with the six pieces above plus its `<key>.docs.yml` (the Sections table cells for docs/reference/sections.md, the COVERAGE.md prose, and the schema descriptions the generators render; the docs loader fails without it), compose the `SettingsFile` property from the slice and add the key to `SECTION_KEYS` in `src/schema.ts`, and add one line in `src/sections/registry.ts` - the compiler flags each forgotten step (the registry's mapped type, the mock fragment registration, the slice composition pin, and the generator aggregation are all keyed by SectionKey).

‎docs/reference/library.md‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,15 @@ The package exports three paths: the entry (`.`), the committed settings.yml JSO
2121

2222
## The API by group
2323

24-
Every name below is exported from the entry, [src/index.ts](https://github.com/Vivswan/github-settings-as-code/blob/main/src/index.ts). Each group has one short example; the types beside each name are in the bundled declarations. Every fallible call returns a [neverthrow](https://github.com/supermacro/neverthrow) `Result` (or `ResultAsync`) whose error is a typed `Problem`; `describeProblem` renders one as the message the action would print. The examples continue from one another: `settings` is the Validate group's validated document, `client` the Client group's `GithubApi`, and `config` in the Io example a `SingleConfig` (the action's parsed inputs).
24+
Every name below is exported from the entry, [src/index.ts](https://github.com/Vivswan/github-settings-as-code/blob/main/src/index.ts). Each group has one short example; the types beside each name are in the bundled declarations.
25+
26+
How a call reports failure depends on its group:
27+
28+
- A call that reads or parses input, or runs a whole flow (`validateSettings`, `readSettingsFile`, `parseRepoSlug`, `mergeLayers`, `discoverRepos`, `parseRecipient`, `runSingle`, `runMulti`, `runMerge`, ...), returns a [neverthrow](https://github.com/supermacro/neverthrow) `Result` (or `ResultAsync`) whose error is a typed `Problem`; `describeProblem` renders one as the message the action would print.
29+
- The engine calls, `checkRepository` and `applyRepository`, always resolve to a report: its `result` field carries the outcome (`clean`, `drift`, `applied`, `partial`, `skipped`, `failed`) and its `outcomes` say what each section did.
30+
- Report delivery: `deliverArtifactReport` never throws and returns `{ uploaded: true }` or `{ warning }`. Two calls throw instead: `encryptReport` on a recipient `parseRecipient` would have rejected (validate it first), and `openReportChannel` when asked for the `artifact` channel without an `ArtifactUploader`.
31+
32+
The examples continue from one another and form one program (the docs tests compile them in page order): each name is imported once, in the first example that uses it, and later examples reuse it, as they do `settings` (the Validate group's validated document), `client` (the Client group's `GithubApi`), and `config` in the Io example (a `SingleConfig`, the action's parsed inputs, declared there).
2533

2634
### Validate and merge
2735

@@ -86,7 +94,7 @@ The run flows the action wraps: `runSingle` (one repository from a local file),
8694
import { concludeMerge, failRun, runMerge, silentIo } from "@vivswan/github-settings-as-code";
8795

8896
const io = silentIo();
89-
const exitCode = runMerge(
97+
const mergeExitCode = runMerge(
9098
{ settingsFiles: ["base.yml", "team.yml"], mergedFile: "merged.yml", layering: "merge" },
9199
io,
92100
).match(
@@ -136,8 +144,9 @@ console.log(labels.key, Object.keys(labels.endpoints), sectionGrant(labels));
136144
`Io` is the output port every flow writes to. `collectingIo()` captures lines, outputs, and summary blocks; `silentIo()` drops them; `prefixedIo(io, prefix)` attributes lines to a target; `maskRegistry` builds the mask pair an `Io` implementation needs.
137145

138146
```ts
139-
import { collectingIo, concludeRun, failRun, runSingle } from "@vivswan/github-settings-as-code";
147+
import { collectingIo, concludeRun, runSingle, type SingleConfig } from "@vivswan/github-settings-as-code";
140148

149+
declare const config: SingleConfig;
141150
const collected = collectingIo();
142151
const exitCode = await runSingle(client, config, collected.io).match(
143152
(target) => concludeRun(collected.io, { kind: "single", mode: config.mode, target }),
@@ -152,4 +161,9 @@ The package and the action share one version, the one in `.release-please-manife
152161

153162
## One-time publishing setup
154163

155-
For the owner, once. npm adds a trusted publisher only to a package that already exists, so the first version is published by hand from a maintainer machine with two-factor authentication: `bun run build:lib` first (the tarball ships `lib/pkg/`, which is built, not committed), then `npm publish --access public`. Then, on npmjs.com, on the package's settings page, add a trusted publisher of type GitHub Actions with owner `Vivswan`, repository `github-settings-as-code`, workflow filename `ci.yml`, and no environment. Then, under publishing access, choose "Require two-factor authentication and disallow tokens", so the workflow's OIDC identity is the only thing that can publish.
164+
For the owner, once. npm adds a trusted publisher only to a package that already exists, so the first version is published by hand from a maintainer machine with two-factor authentication. The bootstrap version is a pre-release published under the `next` dist-tag, so no `latest` exists before the first stable release; the exact version command lands with the publishing workflow.
165+
166+
1. Build the library: `bun run build:lib` (the tarball ships `lib/pkg/`, which is built, not committed).
167+
2. Publish the pre-release under `next`, never `latest`: `npm publish --access public --tag next`.
168+
3. On npmjs.com, on the package's settings page, add a trusted publisher: type GitHub Actions, owner `Vivswan`, repository `github-settings-as-code`, workflow filename `ci.yml`, no environment.
169+
4. Under publishing access, choose "Require two-factor authentication and disallow tokens", so the workflow's OIDC identity is the only thing that can publish.

0 commit comments

Comments
 (0)