--- type: Module title: npm description: The dependency-resolution contracts a manifest library defines but cannot implement, the npm vocabulary shared across the kit, and the registry/tarball/publish services that replace a shelled-out npm CLI. status: stable kind: package resource: ../../packages/npm tags: - architecture - dx generated: by: "okfit/claude-code" at: 2026-11-13T06:27:13Z integrity: generated: body: 6fa4cb9005e8e487 --- # npm ## Purpose `@effected/npm` is an internal package with no source repository predecessor. It owns four things: the dependency-resolution contracts (`CatalogResolver`, `WorkspaceResolver`) that `@effected/package-json` defines a need for but cannot implement, since resolving a `catalog:`/`workspace:` specifier needs workspace and catalog context a document library never has; the cross-cutting npm vocabulary shared by three or more packages (`DependencySpecifier`, `DependencySection`, `IntegrityHash`, `PackageManagerPin`, `PackageManagerCache`); the tolerant `Manifest` domain model built on the per-specifier contracts; and the registry, tarball and publish services (`NpmRegistry`, `PackageTarball`, `PackagePublish`) that do their own IO through core contracts in `R`. See [contract inversion is the default](../decisions/contract-inversion-default.md) for why the contracts live here rather than beside their implementer. ## Tier and dependency posture Boundary tier — not because of an [R2](../conventions/dependency-policy.md) edge (the `@effected/commands` dependency is itself boundary, with zero runtime dependencies, and boundary does not propagate), but because the package performs IO itself through core-declared contracts (`HttpClient`, `ChildProcessSpawner`, `FileSystem`, `Path`, and `Digest` from `effect/crypto`) required in `R` — the same shape `walker`, `xdg` and `git` share. `peerDependencies` is `effect` plus one pure-to-pure `@effected/semver` edge, used only so the range case validates through `Range.FromString`. `dependencies` is `@effected/commands`, `@effected/crypto` (pure `HttpRedaction`, which scrubs the credential out of a kept HTTP cause) and `@effected/glob` (pure, zero-dependency, for `NpmWorkspacePatterns`; a regular dependency because no glob value crosses this package's surface) and nothing else — zero external runtime dependencies. `@effected/package-json`, `@effected/lockfiles` and `@effected/workspaces` all depend on this package; the dependency arrows point at it, never away from it. This package was pure until 2026-07-25, when the registry/tarball/publish services landed; a guardrail keeps it from drifting further to integrated — see [the tier guardrail](../decisions/npm-tier-guardrail.md). ## Module layout Module-per-concept in `src/`, no barrels below `index.ts`. The placements that are decisions rather than mechanics: - `WorkspaceResolver.ts` owns `DependencyResolutionError` (both resolvers raise it); `CatalogResolver.ts` type-imports it, a one-way edge that keeps `noImportCycles` satisfied. - `CatalogAssemblyError.ts` and `PublishError.ts` are leaf modules, not residents of the module that raises them, because two modules must reference each without an import cycle. `PublishError.kind` is `auth | pack | publish | output | digest | executor`; `digest` exists because npm succeeding while the tarball cannot be read back is not "npm pack failed". - `index.ts` owns the composite `Default` layer (both no-op resolver layers merged), the cycle-free home for the merge. - `NpmWorkspacePatterns.ts` is the public face of npm's `workspaces` pattern rules; the engine, with its hostile-input ceilings, is `internal/workspacePatterns.ts`, and its failure is the leaf `NpmWorkspacePatternsError.ts`. See [the section below](#npm-workspace-patterns). - `internal/npmLog.ts` holds the two pure readers of npm's `--loglevel=silly` stderr — the `PublishOutcome.auth` classifier and the `PublishError.output` filter — so both are table-tested without a spawner. Every Effect class factory is written inline, with the synthesized `_base` heritage symbols suppressed narrowly in the bundler's default config per the kit's API Extractor policy. ## Resolver contracts `CatalogResolver` and `WorkspaceResolver` are both `Context.Service` with the shape inlined structurally, and no-op layers bound to a `const` so they memoize by reference. `CatalogResolver.rangeOf` takes a package name and an `Option` catalog name (`None` meaning the default catalog) and answers the configured range, or `None` if unresolvable. `WorkspaceResolver.versionOf` answers the concrete version with the range modifier stripped, or `None`. An unmatched specifier is `Option.none()`, not an error — `DependencyResolutionError` is reserved for mechanism failure, never for "no match found." Its one other case is a `workspace:` specifier naming a known member that declares no `version`, which `none` would misreport as a non-member; a `reason` literal (`"mechanism"`, the constructor and decoding default, or `"no-version"`, raised with no `cause`) separates the two so a consumer never string-matches the wrapped cause, and the `message` getter names the no-version case. `CatalogAssemblyError` is the typed failure of catalog assembly, and it lives beside the contract rather than in the implementing package: the contract package owns the contract's error vocabulary. Before the relocation, `rangeOf` could only name `DependencyResolutionError`, so implementations folded assembly failures into its defect `cause` and every consumer `_tag`-sniffed `unknown` to distinguish an assembly failure from a resolution failure. `@effected/workspaces` implements both contracts directly as layers over its own services, and imports `CatalogAssemblyError` back from here without re-exporting it, so there is exactly one home for it. Its `message` appends the cause's message, since the cause carries the actionable detail and a consumer rendering `message` must not lose it. An optional `reason` (`notInstalled`, `ambiguous`, `fetchFailed`, `integrityMismatch`, `integrityUnavailable`) distinguishes a config dependency that could not be resolved at its declared version (effected#842). ## Manifest: tolerant manifest-level resolution `Manifest` is a `Schema.Class` domain model of a tolerant manifest, offering the manifest-level resolution the per-specifier contracts alone cannot: the four dependency fields are typed `string→string` records and validate — a malformed dependency field, or a non-record input, fails typed — while every other top-level key round-trips unvalidated into a `rest` catch-all, flattened back to the top level on encode so no literal `rest` key ever appears on the wire. Mid-build manifests are arbitrary user records, and forcing them through `@effected/package-json`'s strict `Package` decode would fail resolution on fields this module never reads. The surface is a decode static (normalizing `SchemaError` to `ManifestDecodeError`), a pure `needsResolution` getter (the fast-path predicate letting callers skip catalog assembly entirely), an instance `resolve()` returning a new `Manifest` rather than mutating, and an encode back to the wire shape. `UnresolvedDependencyError` is the manifest-level reading of the contracts' `None` convention: the resolution mechanism worked, the answer was empty, and a manifest with an unanswerable specifier cannot be projected to concrete ranges. Three failure vocabularies meet here and must not blur: `DependencyResolutionError` is failure of the resolution *mechanism*, `CatalogAssemblyError` of catalog assembly, and `UnresolvedDependencyError` the empty answer — its `dependency` names the manifest key, which for a `workspace:@` specifier is the alias whose *target*'s version was resolved. ## DependencySpecifier and the vocabulary modules `DependencySpecifier` is one specifier grammar spanning the kit — lockfiles, workspaces and package-json all classify a specifier the same way. The branded string is the ground truth; a `FromString` codec decodes it to a coarse five-case tagged union (catalog, workspace, semver range, dist-tag, raw fallback), and every union case stores the original raw string so decode∘encode is byte-for-byte identity by construction. Resolution projections — extracting a catalog name, applying pnpm's publish-time workspace projection — are statics here, sharing one internal implementation with the classified instance's own `resolve` so the two can never disagree. The protocol taxonomy (`protocolOf` and friends) classifies eleven specifier protocols; the workspace projection handles the alias form `workspace:@` with a last-`@`, scope-aware split and projects it to `npm:@`, and `workspaceTargetOf` answers the alias target (`None` for the plain form). Range detection decodes `@effected/semver`'s `Range.FromString` purely — the only use of the `semver` edge. Other vocabulary modules: - `DependencySection` — one concept as two literal schemas: the short dependency kinds and the manifest field names, with a single source-of-truth mapping and its derived inverse, replacing private copies package-json, lockfiles and workspaces each carried independently. - `IntegrityHash` — an SRI brand covering two textual forms, because lockfile integrity is not all-SRI: npm, pnpm and bun record SRI, and corepack records its own pin form. `CorepackIntegrityHash` is the corepack-only narrowing shared by identity with `@effected/package-json`'s `PackageManager.integrity` field, so both sides assert against one home — see [consumed by identity](../invariants/corepack-integrity-hash-shared-by-identity.md) for why only a runtime identity assertion can see a re-fork. `SriIntegrityHash` is the sibling narrowing to the SRI `-` form lockfiles record, which rejects a corepack `sha512.` value. It has the same posture: it decodes to the same `IntegrityHashBrand` rather than a second brand, and since the `Schema.check` is erased from the built type, a consumer asserts by object identity that its field schema IS this export. `@effected/workspaces`' `ConfigDependencySpec.integrity` is its first consumer and carries that assertion. `IntegrityHash.isSri` asks the same question of a raw string without decoding; `InvalidSriIntegrityHashError` belongs to the SRI → corepack conversion below, not to this schema. - `PackageManagerPin` — the corepack pin triple `@[+]` as a first-class class, independent of any package.json field, sharing the strict version ruling with package-json's field model but deliberately diverging on the name grammar: the pin vocabulary is a closed three-literal set (npm/pnpm/bun) where the field model is permissive, because corepack itself recognizes only three names (npm, pnpm and yarn) and would reject the real-world `bun@…`, and npm documents no constraint on the field at all. Do not "finish" that consolidation — the divergence is evidence-backed in both modules' TSDoc. The shared version ruling is string-level, through `SemVer.isPinnable`, so a padded substring like `pnpm@ 11.17.0` fails typed with `reason: "version"` where a bare `SemVer.parseResult` check would trim and silently canonicalize; the first `+` after the version always begins the integrity, so a malformed tail fails with `reason: "integrity"` rather than falling back to build-metadata parsing. Prereleases are pinnable; ranges, partials and dist-tags are not. `parseResult` (a sync `Result`) is the primitive under `parse` and the `FromString` codec. - `PackageManagerCache` — the per-manager default-cache-directory facts table: a pure function of manager, platform and home (no IO, no `node:path` — paths join with the platform family's separator) a CI action, a workspace tool or a doctor command can read with no runner, filesystem or subprocess. Three rows, one per supported manager. Every row is cited to the manager's own authority, because prior art in this space was partly folklore and wrong. It is a table of **defaults only**: `$PNPM_HOME`, `$XDG_*`, `$BUN_INSTALL_CACHE_DIR` and npm's `--cache` are deliberately out of scope, and the tests pin every cell — so a "tidied" path never hits. ## SRI-to-corepack conversion npm's SRI form (`sha512-`) and corepack's pin form (`sha512.`) encode the same digest, and converting between them is a real consumer need — writing a `packageManager` pin from a registry read means converting a value the registry hands over in SRI form. The conversion is a `Schema` transformation, `CorepackIntegrityHash.FromSri`, plus an `Effect` convenience `fromSri` failing with a typed `InvalidSriIntegrityHashError`. Non-sha512 input and the wrong digest length both fail typed decode rather than producing garbage a corepack install would reject at the worst possible time. The base64 reader is strict and hand-rolled rather than `Buffer` (Node-only and lenient) or core's `Base64.decode` from `effect/encoding/Base64` (probed: it accepts non-zero trailing bits and embedded CRLF, so three spellings decode to one digest, yet rejects the unpadded form — a drop-in in neither); `Buffer`-style lenience would mint pins corepack rejects at install, and only padding is optional. That verdict is **decode-only**: `PackageTarball` verifies through core's *encoder*, `Base64.encode`, and the codec's encode direction is the exact inverse of its decoder, not a second acceptance rule. The conversion is one-way from SRI: an already-corepack-form input does not pass through decode, so a caller cannot feed pins back in and mask a wiring bug. ## The Node transport: `@effected/npm/node` `NpmRegistry` and `PackageTarball` send every request through the core `HttpClient` in their requirements, and a plain client knows nothing of an npmrc: behind a proxy or against a registry signed by an internal CA every read fails as `RegistryReadError` `"transport"`. The `./node` subpath ships `NpmHttpClient.layer(config, options?)`, the Node HTTP client that applies a resolved `NpmConfig`'s transport settings (proxy, bypass, `ca`, `cafile`, `strict-ssl`, client certificate, `local-address` and each registry's own TLS files). It is `@effect/platform-node`'s undici client over a dispatcher that routes each request by its URL, because the proxy and the client certificate can differ per registry. The decisions are `NpmConfig.proxyFor` and `NpmConfig.tlsFor`, so the layer and the pure methods cannot disagree. `options.packageManager` (`"npm"` default, or `"pnpm"`) picks whose rules decide; a tool replacing `pnpm view` passes `"pnpm"` over `PnpmNpmConfig`, and `options.env` carries the proxy variables, since nothing here reads `process.env`. `NpmConfig.list(key)` answers an array setting's values (`key[]=` lines, or the scalar split as the setting allows), which is how `ca[]` and `noproxy[]` reach the transport. Every file a setting names is read through `FileSystem` when the layer is built, and one that cannot be read, or a proxy that is not an `http`, `https` or `socks5` URL, fails the layer with `NpmTransportError` (`setting` is `cafile`, `certfile`, `keyfile` or `proxy`; a proxy failure carries neither the URL nor the parser's error). The failure is at build, never per request, and a missing `cafile` fails where both managers carry on without it. `@effect/platform-node` is an optional peer, imported only from `src/node.ts`, and no `@effected/*` package depends on `undici` directly; the root entry never reaches it. The built-declaration shape of this second entry point follows the pattern in the `effect-api-extractor-bases` skill. ## Release-age gates pnpm's `minimumReleaseAge` gate, `ReleaseAgeGate`, is pnpm's alone and lives in [`@effected/pnpm`](pnpm.md). npm's own `min-release-age` (days, minimatch excludes, off by default) is a different definition and stays here as `NpmReleaseAge`: `NpmReleaseAge.fromConfig(config)` reads `min-release-age` and `min-release-age-exclude` (array or scalar form, comma-split, trimmed, deduplicated), and the clock is the caller's. The `catalog:` and `workspace:` resolver contracts stay here because bun reads both protocols the way pnpm 12 does; see [the protocol-owner decision](../decisions/catalog-and-workspace-protocol-owner.md). ## The service half: registry reads, tarballs and publishing Three services replace a shelled-out `npm` CLI wherever the work can be done structurally. **`NpmRegistry`** reads over core `HttpClient`, replacing every shelled `npm view`. The model is keyed by `(registry, package, version)` with the registry a per-call argument, never layer-baked, because a publish flow can probe two registries for one package inside a single program. A 404 is `Option.none()`, decided structurally from the response status rather than by matching stderr wording — extending the resolver contracts' `None`-is-success convention to registry reads, and to **every** read: `versions`, `distTags` and `publishTimes` answer `Option` too, `None` for a package the registry does not know and `Some` of an empty list or record for one it knows with nothing listed (a fully unpublished package). They answered an empty collection for both until a consumer could not tell a typo'd catalog entry from an unpublished package (effected#1305). The 404 is not sniffed for a registry's body wording: npm answers `{"error":"Not found"}`, Verdaccio and Artifactory answer other bodies, and a body test would turn a real absence on some registry into a failure, so a proxy's 404 page for something else still reads as absent. The packument's `time` values decode as `Unknown`, because a fully unpublished package carries `time.unpublished` as an object, and a strict string record failed that packument's every read as `decode`. `integrity` is typed as this package's `IntegrityHash`, not a bare string. A per-version read falls back to the whole packument on a 405 from any registry, not just the GitHub Packages case that motivated it (that registry answers the per-version endpoint 405 whatever the credentials, so a `github-packages` target routes through the packument up front), because the routing is by observed behavior rather than a vendor allowlist. Version selection out of a packument uses `Object.hasOwn`: the version number is caller input, and a key like `constructor` must not read the prototype. `RegistryReadError` routes on `kind: transport | status | decode`. Its `registry` field (and the `registry` span annotation) is the registry through `HttpRedaction.url`, so a registry configured as `https://user:pass@host` keeps no userinfo or credential query value on the error; `PublishError.registry` and `PackagePublish`'s span annotations get the same treatment. The service wraps its client in core's `HttpClient.followRedirects`, as `PackageTarball` does and for the same reason: the origin-change rule (core drops `authorization`, `proxy-authorization` and `cookie` on a cross-origin hop, scheme, host or port) then holds whichever client the consumer provides, so a registry that hands a read off to a mirror or CDN never forwards the credential, while a same-origin hop keeps it. A fetch client that follows redirects itself returns no 3xx, so the wrap adds nothing there. A transport or decode failure keeps core's `HttpClientError` as `cause` only through `@effected/crypto`'s `HttpRedaction.cause`, because core's error holds the live request, `authorization` header included, as a readable field and redacts it only when rendering. **`NpmRegistry.manifest(name, version)`** answers a `VersionManifest` — `name`, `version` and, each absent when the document does not declare it, `dependencies`, `peerDependencies`, `optionalDependencies`, `peerDependenciesMeta` and `engines` — through the same per-version routing as `version` (one internal `versionDocument` reader, generic over the schema, owns the github-packages-first and 405-fallback rule, so the two reads cannot reach one version by different paths). It is a separate read rather than more fields on `PublishedVersion` so a publish probe never validates dependency records it does not read, and so a malformed record in an old version cannot turn "is this published?" into a failure. Its consumer is a catalog resolver that lists versions and then prefetches every candidate's peers (rolldown-pnpm-config's `upgrade`, effected#1170): with versions and times from the kit and peers from `pnpm view`, one package resolved through two registry/auth paths that could disagree. The four dependency fields decode strictly — a malformed one fails `decode`, because reading it as absent would answer "no peers" for a version that has them — while `engines` is kept only as a string record and otherwise omitted, because old publishes carry the legacy array form and an advisory field must not fail a peer read. The exported `VersionManifest` class is the decoder seam for a consumer holding a raw document, strict on `engines` too; the service's leniency is applied by decoding through an internal struct that takes `engines` as `Unknown`. Two doubles ship: `layerTest(Partial)`, whose unstubbed members die rather than answer a fake default, and `layerSeeded(RegistrySeed)`, a working fake keyed on all three axes `registries[registry][name][version]` — a double keyed by package name alone cannot express two registries disagreeing about one package, which is the case the publish flow exists to probe. **`PackageTarball`** is the inbound half — `NpmRegistry` reads metadata and `PackagePublish` sends a tarball out, but nothing previously read a published one back. `changelog(target, name, version)` reads `package/CHANGELOG.md` out of a published tarball in memory, with no file system and no `tar`, answering `Option` (`None` for an unpublished version, a tarball that answers 404 or an archive without the file, matched exactly and case-sensitively). The archive is untrusted: download and inflated bytes are each capped at 256 MiB and a corrupt or oversize one fails `RegistryReadError` `"decode"`. `extract` takes a `PublishedVersion` and yields, inside a `Scope`, the directory the tarball's fixed `package/` root unpacked into. Integrity is verified before extraction and before anything reads the contents, using core's `Digest.Digest` and `Base64.encode` from `effect/encoding/Base64`; a non-2xx is caught before anything reaches disk, since piping a 404 error page into `tar` would surface as a misleading "could not extract." The digest compare is padding-insensitive, since the SRI grammar permits an unpadded value; an integrity form this cannot check (one that names no algorithm) logs a warning that it could not verify rather than skipping silently, and a digest that could not be computed (core's `Digest` dies without `crypto.subtle`) is a defect, never an `integrityMismatch`, because nothing was compared; either way the bytes never reach `tar`. `TarballError.reason` (`notFound | http | integrityMismatch | extractFailed`) is discriminated rather than collapsed to one sentinel, because a consumer that cannot tell "this version legitimately does not exist" from "something went wrong fetching a version that does" treats both the same way — an incident where an integrity mismatch was handled as a missing merge base, downgrading a merge to a lossy algorithm and dropping a user's override on a run that reported success, is the standing argument against collapsing it. Extraction shells out to `tar` through core's `ChildProcessSpawner` rather than taking a tarball-reader library dependency — see [the tier guardrail](../decisions/npm-tier-guardrail.md) for why that is a tier decision, not a convenience. **A private-registry tarball authenticates by its own URL.** `extract(published, { credentials })` takes a `RegistryCredentialLookup` — `credentialFor(url): Option`, which `NpmConfig` satisfies as it stands — and asks it once, for `published.tarball`, never for the registry or the package. That is npm's own scoping, and it matters because a tarball is often served from another host than the registry that listed it (a CDN, GitHub Packages' signed-URL storage host): a lookup keyed by the registry would send the registry's token there. The option is a lookup rather than a bare `RegistryCredential` deliberately, since a bare credential carries no URL and the easy call would pass the registry's token through. No match proceeds unauthenticated, as npm does, and a registry that wanted a credential answers 401/403, which fails `http` with that `status`; a lookup that answers a workload credential (a caller cast past the type) sends nothing rather than spending a publish credential on a read. The service wraps the client in core's `HttpClient.followRedirects`, so redirects are followed whichever client the consumer provides (a fetch client that follows them itself returns no 3xx, so the wrap adds nothing there), and core's origin rule drops `authorization` on a cross-origin hop — scheme, host or port — while a same-origin hop keeps it. The credential never reaches an error, a log line or a span: the header is never logged or annotated, core serializes a request without headers, a kept transport or body-read cause is a `HttpRedaction.cause` copy whose `authorization` reads `REDACTED`, and the suite walks every string reachable from the error, core `Headers` included (core redacts them only when rendering, so a walking logger would otherwise read the token), against a positive control that the walk finds the token on core's own error, as well as capturing logs at every level and every span. **`PackageTarball.changelog(target, name, version)`** is the in-memory sibling: it reads the version through `NpmRegistry`, downloads the tarball and answers the text of `package/CHANGELOG.md` as an `Option`, with `NpmRegistry` and `HttpClient` in `R` (no `FileSystem`, no `tar`), so the caller's configured or seeded registry is the one read. `internal/tarEntry.ts` inflates through `DecompressionStream` under a 256 MiB cap (pnpm's `MAX_TARBALL_BYTES`) and walks the tar headers, taking ustar prefixes, pax `path` and GNU long names; the match is exact and case-sensitive like pnpm's `extract_entry`. A corrupt or oversize archive is `RegistryReadError` kind `decode`, never a defect; 404s and an absent file are `None`; the credential goes to the tarball only on the registry's own origin. Integrity is not verified (one text file is read, nothing is written or run). Loading the extracted file is deliberately not part of this surface, since a dynamic `import()` of a computed path becomes a bundler context module; the composition instead pairs this with `@effected/package-json`'s pure `resolveEntryPoint` and leaves the load to the consumer's own bundler-visible code. **`RegistryCredential`** is a closed union (`{ kind: "token" }` or `{ kind: "basic" }`) taken by both the read probe (`RegistryTarget.credential`) and `PackagePublish.setupAuth`, because a probe and a publish disagreeing about the authentication scheme against the same registry is the worst kind of bug: a bearer probe against a basic-auth registry answers 401, which reads as "not published," so a publish proceeds on a false premise. `setupAuth` takes the wider **`PublishCredential`** — `RegistryCredential` plus the publish-only **`WorkloadCredential`** (`{ kind: "workload", audience, token }`, a CI identity token behind a registry prefix, built by the pure `workloadCredential`). The superset is a separate name rather than a widened `RegistryCredential` so that every read site already typed `RegistryCredential` keeps compiling and keeps refusing a workload credential at compile time; `NpmRegistry` also refuses one at runtime (`RegistryReadError` kind `"credential"`, before any request, in the live service and the seeded double alike) for a caller that casts past the type. Minting and masking the identity token cannot live here — the Actions token issuer and the log mask are in `github-actions`, which depends on this package — so `ActionsRegistryCredential.workload` in that package mints, masks both values and calls `workloadCredential`. The basic arm holds the already-encoded blob npm itself stores in `_auth`, never a user/password pair; `basicCredentialFromPairResult` mints one for the caller who genuinely holds a pair and returns a typed `BasicCredentialError` (`"colon-in-username"`) rather than throwing, because the username is runtime data and a throw from a pure helper escapes an `Effect.gen` as a defect. The kind picks the npmrc key (`_authToken` for token and workload, `_auth` for basic) through an exhaustive switch — a `kind === "token"` ternary sent every other kind to `_auth` — and the header scheme; the kind and a workload's audience are span-annotated, the value never is. `setupAuth` always upserts: it replaces the first line with the same `//host/:_authToken=` or `_auth` key in place, removes later duplicates and the same registry's other-scheme key, appends only when nothing matches, and leaves every other line untouched. It has no append mode, because npm reads the first matching key: a short-lived credential re-minted per publish target (a GitHub ID token forwarded to a registry as a workload credential) would otherwise pile up duplicate keys and be silently shadowed by the stale first one. `RegistryTarget.token` survives one minor as a deprecated `never` tripwire rather than being dropped silently or aliased, because a caller's conditional spread of a no-longer-known property compiles clean and drops the field with no error — typed `never` makes that spread a compile error instead. **`NpmExecutor`** carries `withCacheDir` and a generic `withExtraArgs`, both copy-returning; `withExtraArgs` replaces rather than accumulates. `dlx(spec)` runs through `@effected/commands`' `LocalExec.applyDlx` (`pnpm dlx npm@11 …`) because OIDC trusted publishing needs npm ≥ 11.5.1 and GitHub-hosted runners ship 10.x. The cache redirect is named API, not tribal knowledge, because GitHub's macOS runner images ship a partially root-owned `~/.npm/_cacache` and current npm hard-fails `EACCES` on sight of it — an environment variable fixes it identically, but invisibly, which is how the fix gets lost in a port and rediscovered the hard way. The redirect overrides a deliberately configured cache (a `--cache` flag in argv outranks both `npm_config_cache` and any npmrc setting), and the combinator stays dumb about ambient state on purpose: a value transformation that reads ambient state cannot be reasoned about from the call site. **`PackagePublish`** collapses a repeated per-method package-manager option into one `NpmExecutor` value (ambient or dlx), because `@effected/commands` already models fetch-and-run of a package binary. OIDC trusted publishing needs a fresh npm rather than the runner's bundled one, so `dlx` fails typed when no launcher is available rather than degrading to the ambient npm — degrading would reintroduce the exact OIDC failure the pinned spec exists to avoid, invisibly. Auth setup writes the credential into a caller-supplied npmrc path rather than argv, because redaction protects this kit's error messages, not the operating system's process table, and keeping the token off argv stays the security-correct choice regardless; masking the value is the caller's job, since this package takes no `ActionOutputs` edge. `pack` reports two digests that are **not interchangeable**: `integrity` is npm's sha512 SRI, the value that compares against the registry's `dist.integrity`, and `sha256Hex` is a local hex sha256, the attestation subject. Its `pack --json` decoder accepts both the npm 11 array and the npm 12 name-keyed object — see [the npm 12 gotcha](../gotchas/npm-12-pack-json-is-keyed-by-name.md). A failed `dryRun` is a **result**, not an error. On a result record the fields match their neighbours' optionality: `PublishOutcome.provenanceUrl` is a plain optional field, not an `Option`, because as an `Option` a bare `=== undefined` check compiled clean, was always true, and bit a consumer live — `Option` discipline is for the resolver contracts, where `None` is the answer. `PublishOutcome.auth` (`"oidc-exchange" | "configured-credential" | "unknown"`) is **required**, because every run can answer at least `"unknown"` and an optional field would let a test double say nothing where production says something. npm names its auth path only below its default log level, so `publishTarball` runs at `--loglevel=silly` (overriding an npmrc or environment `loglevel`; only an executor `extraArgs` flag wins) and reads the answer from stderr on positive evidence only, while a failure's `PublishError.output` is filtered back to the default levels — see [the auth-path gotcha](../gotchas/npm-oidc-auth-path-is-verbose-only.md). `tokenAuth` blanks all three identity-token variables (`NPM_ID_TOKEN` is read before the Actions token service) and drops `--provenance`, which on GitHub Actions needs the token service the option blanks. `PackagePublish.recording()` is a recording sibling of `layerTest` that journals each `setupAuth` call's registry, npmrc, kind and audience, never the value. A fused probe-then-publish convenience is deliberately absent: the composition it would replace is consumer composition, and a fused form would hardcode one registry and could not recover from a partial multi-registry publish. **The npmrc transport settings are read here and applied by the caller.** `NpmRegistry` and `PackageTarball` own no connection, so proxy, bypass, TLS and local-address settings take effect only in the `HttpClient` the caller provides. `NpmConfig.transport` reads the top-level ones as an `NpmTransportSettings` record, the superset of what npm (11 and 12 alike) and pnpm read, with each field naming its reader: pnpm adds `http-proxy`, `no-proxy` and `proxy=false` as "no proxy at all". Proxy URLs (userinfo kept, since `settings` holds them stripped) and the inline `cert`/`key` are `Redacted`. `strict-ssl` is off only for the literal `false` under both managers. An `isDefault` getter serves a caller that wants to warn. `NpmConfig.tlsFor(url, { packageManager })` answers a registry's own `//host/:ca|cafile|cert|certfile|key|keyfile` (`NpmRegistryTls`) by npm's matching (the credential walk, stopping at the first key holding any auth, answering only the `certfile`/`keyfile` pair) or pnpm's (slash-terminated directory keys, then without the port, all six fields), because an npmrc written for pnpm keeps its TLS per registry. Every proxy key's userinfo is removed from `settings` whether or not the URL has a scheme. Top-level `certfile`/`keyfile` are not held, because neither manager reads them and npm 12 refuses them. `NpmConfig.proxyFor(url, env, { packageManager })` resolves the proxy by npm's rules or pnpm's, since the two route one npmrc differently: scheme-split proxies, the `proxy=false` off switch, `no-proxy` and env-case rules. The kit ships no proxy-aware client, because the dispatcher it needs is a Node-only dependency this boundary package must not take. See [the transport limitation](../limitations/npm-registry-applies-no-transport-settings.md) for the per-manager detail, the source citations and the recipe (effected#1307). **`RegistryKind`** replaces four boolean predicates with one exhaustive classification (`npm | github-packages | jsr | custom`); the domain match is exact-or-subdomain with a leading dot, because a bare `endsWith` would classify a lookalike domain as the public registry and that classification decides whether a token is sent. Two label projections (`registryShortLabel` — `npm`/`github`/`jsr`, else the host — and `registryDisplayName` — `npm`/`GitHub Packages`/`JSR`, else the host) ship beside the classifier as functions over the registry string rather than a lookup table, so the same leading-dot domain guard covers the labels too; both fall back to the shared `registryHost`, which **keeps the port**, unlike the hostname the classifier compares. `registryDisplayName` accepts absent-or-empty and answers `npm`; `registryShortLabel` takes a plain `string`, so a nullish value is a compile error. **`NpmConfig`** resolves the user's npm configuration so a registry read honours `.npmrc` the way the npm CLI does — scoped registries and per-host credentials — instead of a consumer shelling out to `pnpm view` and scraping its notices (rolldown-pnpm-config's catalog `upgrade`, effected#1132). It is not a second registry client: it produces a `RegistryTarget`, and `NpmRegistry` sends the credential the established way, the same `RegistryCredential` union a publish writes. The pure core is `NpmConfig.fromSourcesResult(sources, env, options?)` (npmrc texts, lowest precedence first, with `npm_config_*` on top unless `options.npmEnvironment` is `false`, which `@effected/pnpm`'s `PnpmNpmConfig` sets because pnpm 12 reads no `npm_config_*` setting and supplies its own layers as sources); `NpmConfig.load({ cwd, env, home?, globalPrefix? })` is the IO shell over `FileSystem` and `Path` in `R`, reading the project npmrc (by default npm's `localPrefix`: the nearest directory holding a `package.json` or `node_modules`; `projectDir` names the directory outright, and `workspaceRoot: true` ascends to the nearest `pnpm-workspace.yaml` or `package.json` with a `workspaces` field, falling back to the default when there is none — `projectDir` wins when both are set, and relative `userconfig`/`globalconfig`/`prefix` settings resolve against whichever directory was chosen), the user npmrc (`userconfig`, else `~/.npmrc`) and the global npmrc (`globalconfig`, else `/etc/npmrc`, with the prefix from a setting or the caller — never guessed from the running Node). The environment arrives as a plain record so nothing here reads `process`. A missing file is skipped, as npm skips it; an unreadable one fails `NpmConfigError` `"read"`. **The credential rule is the load-bearing part: a credential only ever goes to the host it was configured for.** `credentialFor(url)` is npm-registry-fetch's lookup (`regFromURI` behind `getAuth` in `lib/auth.js`, read at 19.1.1): the nerf-dart key of the URL being requested (host lowercased and a default port dropped by `URL`), walked up through parent paths to `//host[:port]` and never further, `_authToken` before `_auth` before `username` + base64 `_password` within the first key that holds one. npm starts at `//host[:port]` plus the whole path and strips either the trailing non-slash run or one trailing `/` per step, so every level is tried with its trailing slash and then without it: `https://h/a/b.tgz` tries `//h/a/b.tgz`, `//h/a/`, `//h/a`, `//h/`, `//h`. An npmrc written `//host:_authToken` or `//host/path:_authToken` (which `@npmcli/config` does not rewrite) is therefore found, and when both spellings of one level are configured the slash form wins because it comes first, while a deeper slash-less key still beats a shallower slash key. Every key ends on a segment boundary of the request's own host and path, so a slash-less key cannot widen a match: `//host` never matches `//hostevil.com`, `//host/pa` never matches `/path/`. The kit tried only the trailing-slash keys until a review found a working npm config silently sending no credential through it. `internal/nerfDartKeys.ts` builds npm's list without stripping, a single scan of `/` positions capped at the 64 shallowest keys, and a test compares it against a transcription of npm's walk. An empty segment is a level of its own: an Artifactory or Nexus tarball at `https://host//pkg/-/x.tgz` walks down through `//host//pkg/`, `//host//pkg`, `//host//`, `//host/` and `//host`. The walk this replaced stripped `[^/]+/$` until it reached `/`, and on `//` it never did: a registry-controlled `dist.tarball` holding `//` spun `PackageTarball.extract` until the process ran out of memory. A subprocess test with a hard timeout pins the termination, since a vitest timeout cannot stop a synchronous loop. So a scoped registry on another host, a lookalike host, another port, and a tarball URL on a CDN get nothing unless that host has its own entry, and an unscoped top-level `_authToken` names no host and is never used. `targetFor(name)` looks the credential up for the package's own request URL rather than the registry string, which is what finds a path-scoped token (`//npm.pkg.github.com/acme/`) for a registry written without a trailing slash. A cross-origin HTTP redirect is the client's half: core's `HttpClient.followRedirects` drops `authorization` on an origin change and fetch does the same, and the suite pins the former through `NpmRegistry`. **The scheme rule departs from npm on purpose: a credential goes over `https:` only.** npm matches the nerf-dart key and ignores the scheme, so a token configured for a host also goes to `http://` and `ws://` on that host, in cleartext. `credentialFor` answers `None` for any scheme but `https:`, except `http:` to a host and port that a configured registry (`registry` or an `@scope:registry`) itself names with an `http:` URL — the one explicit way a config says it means cleartext, which is what a local Verdaccio on `http://localhost:4873/` needs. A security review found the scheme gap; the fix is pinned in both directions. **Every secret-bearing setting is `Redacted`, not only the three credential fields.** `secrets` holds `_authToken`, `_auth`, `_password`, an inline `key` or `cert` (PEM text in the npmrc), and the as-written value of any setting whose URL carried userinfo (`registry=https://user:pass@host/`); `settings` keeps that URL with the userinfo removed, textually, so the rest is exactly as written. A higher layer replaces a key in both maps, so a lower layer's userinfo cannot outlive the URL that carried it. Userinfo is not turned into a credential: configure `_auth` for the host. Nothing reads `certfile`/`keyfile` contents (client certificates are unsupported), so only their paths are held, as settings. **`parseNpmrc` / `npmrcValue` / `NpmrcEntry`** (`src/Npmrc.ts`, root export — the package has one entrypoint, and the module is pure, so it costs a JSON-only consumer nothing) are the `.npmrc` text parser `NpmConfig` runs on, public for a consumer that needs one file's settings without the layered resolution (#1272). `parseNpmrc(text, env)` returns `NpmrcEntry` values (`key`, `value`, `unset`) in file order and cannot fail; `${VAR}` expansion follows npm's `env-replace` (unset `${VAR}` left as written and listed in `unset`, `${VAR?}` emptied, odd backslash run escapes). `unset` covers the key and the value. `key[]=v` lines come back as `array: true` entries (key without `[]`, as ini names it), and `NpmConfig` skips them. `npmrcValue(entries, key)` is the scalar lookup: `Option`, last occurrence wins, array entries never answer it; `npmrcValues` returns an array setting's values (empty list when absent). The `"missing-env"` credential rule stays in `NpmConfig`, built on `unset` (so an unset `${VAR}` in a credential key fails it too). Two deliberate departures from npm. A credential value naming an unset `${VAR}` fails `"missing-env"` naming the variable, key and file: npm leaves the literal `${VAR}` in place and sends it as the token, which turns a missing CI secret into a confusing 401; an ordinary setting keeps npm's literal behaviour. And credentials are stored as `Redacted` in a separate `secrets` map, so printing or serializing a config shows ``, and the error message never carries a value, only names. Unsupported, and documented as such on the class: command-line flags, the builtin npmrc, client certificates and `always-auth`. Workspace-root discovery is opt-in rather than the default, because the default must stay npm's own lookup; it exists because a pnpm workspace run from a member package otherwise misses the root `.npmrc` pnpm honours there (effected#1170). Its ascent is done on core `FileSystem` and `Path` rather than `@effected/walker`, which this package does not depend on, and a `workspaces` field counts as a marker without matching its globs against `cwd` (npm checks membership; matching would need a glob dependency for a case the nearest-marker rule already gets right in practice). A `package.json` that cannot be read or parsed, or whose `workspaces` is not an array or object, is not a marker. Keys go through `Object.defineProperty`, so a `__proto__` line stays an own property. Both services follow the kit's service conventions: all-effectful shapes, `static readonly layer` using `this`, named spans on public boundaries carrying package name, registry host and version — never a token, never argv. Service `R` is discharged at construction, so every method's own `R` is `never`. ## The package-lock.json document `PackageLockDocument` is `package-lock.json` as npm writes it, `lockfileVersion` 3 and newer: `name`, `version`, `lockfileVersion`, `requires` and the `packages` map keyed by install position. `PackageLockDocument.parse` reads text through native `JSON.parse` inside the typed channel. It gates `lockfileVersion` before the shape decode, so a v1 tree with no `packages` object fails as too old rather than as malformed. The document is pure and reachable from the root.[^package-lock-document-ts] Normalising it into a manager-neutral model is `lockfiles`' job. `LockfileDocumentError` is the one failure of every manager package's document parser: this one, `pnpm`'s `PnpmLockDocument` and `PnpmEnvDocument`, and `bun`'s `BunLockDocument`. It lives here because all three depend on this package. Its `reason` is `syntax | framing | shape | version`, and each reason carries its own fields: `line` and `cause`, `framing` and `documents`, or `lockfileVersion` and `minimumSupported`. Those fields are what lets `lockfiles` map it into its public `LockfileParseError` / `LockfileFramingError` without losing anything. ## npm workspace patterns `NpmWorkspacePatterns.matcherResult(field)` is the kit's one reading of an npm `workspaces` field, as `@npmcli/map-workspaces` 5 reads it with the glob 13 `Ignore` it hands negations to (#1286). It returns a predicate over normalized relative directories, or an `NpmWorkspacePatternsError` naming the ceiling the field passed (`tooManyPatterns`, `tooManyWildcards`, `patternTooLong`, `tooManyAlternatives` with an `exact`/`stopped`/`inexact`/`unbounded` `count`, or `uncompilable` carrying glob's error). The rules, each pinned against `npm query .workspace` on npm 11.20.0 by `@effected/lockfiles`' fixtures, and the measured ceilings are recorded in [the lockfiles module](lockfiles.md), where they were ruled (#1267). The matcher moved here so that no second copy can drift from it. It is pure vocabulary, listed in `__test__/reachability.test.ts`, and lives here rather than in `@effected/workspaces` despite the registry's "workspace semantics → workspaces" assignment. `@effected/lockfiles`, the first consumer, is pure and already depends on this package, while `@effected/workspaces` is integrated: housing it there would pull lockfiles up a tier. The rules are npm's, not `GlobSet`'s set semantics: the two readings disagree on ordered negation, a trailing `/` on a positive or a negation, an even run of `!`, and a backslash in a positive. `@effected/workspaces`, the second consumer, reads an npm root's `package.json#workspaces` through it and a bun root's, or a yarn repository's, through `GlobSet` (#1329). ## Vocabulary registry Four packages — npm, package-json, lockfiles, workspaces — operate around overlapping npm concepts, and API ships on evidence: an unmodeled concept stays unmodeled until a second consumer materializes, but a registry records where every modeled concept lives so nobody rebuilds an idiom for lack of a map. Standing assignments: versions and ranges → `@effected/semver`; manifest shapes → `@effected/package-json`; lockfile shapes → `@effected/lockfiles`; workspace and monorepo semantics → `@effected/workspaces`; cross-cutting scalars flowing between those concerns → here. Anything not modeled is preserved verbatim by the manifest or lockfile layer rather than discarded. Two standing rulings: `PackageName` stays in `@effected/package-json` until a second consumer materializes, and the pnpm `catalogs:` record shape is not pre-claimed here — it routes to `@effected/lockfiles`. ## Consumers and implementers Consumers today are `@effected/package-json` (`Package.resolve`, and re-exporting `DependencySpecifier`), `@effected/lockfiles` (which pulled `DependencySpecifier`, `DependencyField` and `IntegrityHash` here as the second consumer) and `@effected/workspaces`. Arrows point *at* this package; the only outbound edges are the pure `@effected/semver` peer and the boundary `@effected/commands` dependency. `@effected/workspaces` implements both contracts as layers over its own services — `WorkspaceCatalogs.catalogResolver` and `WorkspaceDiscovery.workspaceResolver` — and its `Workspaces.resolverLayer` / `Workspaces.resolveManifest` are the batteries-included path over `Manifest`. It also surfaces the release-age contract (`WorkspaceCatalogsShape.releaseAgeGate`, `HookInjection.releaseAge`) that it cannot own, which is why the gate vocabulary lives here. ## Testing Suites in `__test__/` per concept. Shared layers are provided through a top-level `layer(...)`, never per-test `Effect.provide`, and stubs build `Option` results with `Option.fromUndefinedOr`. The resolver-contract tests are light — no-op layers answer `None`, a stub-implementation layer proves the contract is implementable, and the resolution error preserves its structured cause — while the vocabulary tests carry the weight: specifier classification across the protocol set, the round-trip property, resolution projections, the section mapping, integrity across both forms and the release-age gate's strictest-wins/union/totality behavior. Registry reads run against a stubbed core `HttpClient`, no platform package involved, and `Interruption.test.ts` runs them over the real `FetchHttpClient` to pin that an interrupted read aborts its fetch, request or body, through core's own per-request `AbortController` (the package adds no wiring); publishing runs against `@effected/commands`' scripted-spawner fixture, which records argv, so "the token never reached argv" is an assertion rather than a hope. The auth classifier and the failure-output filter are table-tested over recorded npm transcripts, including the precedence case (an exchange followed by a provenance failure) that kills a first-marker-wins reading, and the workload `setupAuth` and read refusal are mutation-checked against the ternary and the missing guard they replaced. The tarball suite uses `@effected/memfs` as a devDependency so a write failure is a test input rather than a stub body, and its discriminating claims are ordering claims — a mismatched digest fails before anything is written, and a non-2xx never reaches the extractor. ## Build Every Effect class factory is inline with no exported `*_base` const; the bundler's default config suppresses `ae-forgotten-export` for the `_base` pattern, so a clean `dist/prod/issues.json` carries empty `warnings`/`errors` and one `suppressed` entry per such class. An empty `suppressed` means the meta pass did not run. `pnpm build --filter @effected/npm` runs the build [through turbo](../conventions/build-through-turbo-only.md). [^package-lock-document-ts]: `packages/npm/src/PackageLockDocument.ts` and `LockfileDocumentError.ts`; the tests are `__test__/PackageLockDocument.test.ts`, over copies of `lockfiles`' fixtures with a provenance README.