@effected/changesets 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Ledger.js ADDED
@@ -0,0 +1,200 @@
1
+ import { LedgerError } from "./errors.js";
2
+ import { Effect, FileSystem, Option, Path, Result, Schema } from "effect";
3
+ import { Yaml } from "@effected/yaml";
4
+
5
+ // src/Ledger.ts
6
+ /** `./`-less, `/`-separated, no trailing `/`: pnpm's `normalize_project_dir`. */
7
+ const normalizeProjectDir = (dir) => {
8
+ let normalized = dir.replaceAll("\\", "/");
9
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
10
+ let end = normalized.length;
11
+ while (end > 0 && normalized[end - 1] === "/") end--;
12
+ return normalized.slice(0, end);
13
+ };
14
+ /** Build metadata (after `+`) may contain hyphens and never makes a version a prerelease. */
15
+ const isPrerelease = (version) => (version.split("+")[0] ?? "").includes("-");
16
+ /**
17
+ * One consumed release in the ledger: the package, the version it released,
18
+ * the project directory, and the ids of the intent files that release
19
+ * consumed.
20
+ *
21
+ * @public
22
+ */
23
+ var LedgerEntry = class extends Schema.Class("LedgerEntry")({
24
+ /** The package name; a scoped name keeps its `@scope/`. */
25
+ name: Schema.String,
26
+ /** The released version, the part of the ledger key after its last `@`. */
27
+ version: Schema.String,
28
+ /**
29
+ * The released project's workspace-relative directory as recorded, the
30
+ * engine's unit of identity. Absent on an entry written as a bare list of
31
+ * ids, which names no directory.
32
+ */
33
+ dir: Schema.optionalKey(Schema.String),
34
+ /** The ids (file names without `.md`) of the intents the release consumed. */
35
+ intents: Schema.Array(Schema.String)
36
+ }) {};
37
+ /**
38
+ * Split `name@version` on the LAST `@` after position 0, as pnpm's
39
+ * `split_ledger_key` does, so a scoped name keeps its leading `@`.
40
+ */
41
+ const splitKey = (key) => {
42
+ const at = key.lastIndexOf("@");
43
+ return at > 0 ? Option.some([key.slice(0, at), key.slice(at + 1)]) : Option.none();
44
+ };
45
+ const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
46
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
47
+ const invalid = (key, why) => new LedgerError({
48
+ code: "invalid-entry",
49
+ detail: `${key}: ${why}`
50
+ });
51
+ const toEntry = (key, name, version, value) => {
52
+ if (value === null || value === void 0) return Result.succeed(LedgerEntry.make({
53
+ name,
54
+ version,
55
+ intents: []
56
+ }));
57
+ if (Array.isArray(value)) return isStringArray(value) ? Result.succeed(LedgerEntry.make({
58
+ name,
59
+ version,
60
+ intents: [...value]
61
+ })) : Result.fail(invalid(key, "an intent id list must hold strings"));
62
+ if (!isRecord(value)) return Result.fail(invalid(key, "an entry is a list of intent ids or a dir/intents mapping"));
63
+ const dir = Object.hasOwn(value, "dir") ? value.dir : void 0;
64
+ if (typeof dir !== "string") return Result.fail(invalid(key, "a mapping entry needs a string \"dir\""));
65
+ const intents = Object.hasOwn(value, "intents") ? value.intents : void 0;
66
+ if (intents !== null && intents !== void 0 && !isStringArray(intents)) return Result.fail(invalid(key, "\"intents\" must be a list of strings"));
67
+ return Result.succeed(LedgerEntry.make({
68
+ name,
69
+ version,
70
+ dir,
71
+ intents: intents === null || intents === void 0 ? [] : [...intents]
72
+ }));
73
+ };
74
+ /**
75
+ * The decoded `.changeset/ledger.yaml`: pnpm's committed, append-only record
76
+ * of which intent files each release consumed.
77
+ *
78
+ * @remarks
79
+ * pnpm does not delete an intent file when a release consumes it. The file
80
+ * stays until every project it names has released, so whether an intent is
81
+ * still pending is a per-project question: an intent is pending for a project
82
+ * exactly when no ledger entry for that project lists its id. Entries are
83
+ * matched to a project by `dir` (the engine's unit of identity, since package
84
+ * names may collide across projects, and a package may be renamed), never by
85
+ * the name in the key; only an entry written as a bare id list carries no
86
+ * `dir` and is matched by name. The file maps
87
+ * `<name>@<version>` to `{ dir, intents }` or to a bare list of ids; a key
88
+ * with no `@` after its first character is skipped, as pnpm skips it.
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * import { Effect, Option } from "effect";
93
+ * import { Ledger } from "@effected/changesets";
94
+ *
95
+ * // `FileSystem` and `Path` come from the platform layer at the edge.
96
+ * const program = Ledger.read("/repo").pipe(
97
+ * Effect.map(Option.map((ledger) => ledger.consumed("calm-cats-resolve", "@example/core"))),
98
+ * );
99
+ * ```
100
+ *
101
+ * @public
102
+ */
103
+ var Ledger = class Ledger extends Schema.Class("Ledger")({
104
+ /** Every release the ledger records, in file order. */
105
+ entries: Schema.Array(LedgerEntry) }) {
106
+ /**
107
+ * Parse the text of a ledger. A blank file is an empty ledger. Fails with
108
+ * {@link LedgerError} on text that is not YAML, a document that is not a
109
+ * mapping, or an entry of the wrong shape; never throws.
110
+ *
111
+ * @param text - The contents of `.changeset/ledger.yaml`.
112
+ */
113
+ static parseResult(text) {
114
+ if (text.trim() === "") return Result.succeed(Ledger.make({ entries: [] }));
115
+ const parsed = Yaml.parseResult(text);
116
+ if (Result.isFailure(parsed)) return Result.fail(new LedgerError({
117
+ code: "invalid-yaml",
118
+ detail: parsed.failure.message
119
+ }));
120
+ const document = parsed.success;
121
+ if (document === null || document === void 0) return Result.succeed(Ledger.make({ entries: [] }));
122
+ if (!isRecord(document)) return Result.fail(new LedgerError({
123
+ code: "not-a-mapping",
124
+ detail: "the ledger must map name@version to a release"
125
+ }));
126
+ const entries = [];
127
+ for (const [key, value] of Object.entries(document)) {
128
+ const split = splitKey(key);
129
+ if (Option.isNone(split)) continue;
130
+ const entry = toEntry(key, split.value[0], split.value[1], value);
131
+ if (Result.isFailure(entry)) return Result.fail(entry.failure);
132
+ entries.push(entry.success);
133
+ }
134
+ return Result.succeed(Ledger.make({ entries }));
135
+ }
136
+ /**
137
+ * Read `<root>/.changeset/ledger.yaml`: `Option.none()` when the file does
138
+ * not exist, which is the state of a repository pnpm has not yet released.
139
+ *
140
+ * Fails with {@link LedgerError} when the file is malformed.
141
+ *
142
+ * @param root - The repository root.
143
+ */
144
+ static read = Effect.fn("Ledger.read")(function* (root) {
145
+ const fs = yield* FileSystem.FileSystem;
146
+ const path = yield* Path.Path;
147
+ const text = yield* fs.readFileString(path.join(root, ".changeset", "ledger.yaml")).pipe(Effect.map(Option.some), Effect.catch((error) => error.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(error)));
148
+ if (Option.isNone(text)) return Option.none();
149
+ return Option.some(yield* Effect.fromResult(Ledger.parseResult(text.value)));
150
+ });
151
+ /**
152
+ * Whether a BARE-LIST entry for the package called `name` consumed the
153
+ * intent. As pnpm does, an entry that records a `dir` is never matched by
154
+ * the name in its key (a renamed or reused name would answer for the wrong
155
+ * project): use {@link Ledger.consumedDir} or {@link Ledger.consumption}
156
+ * for those. Only an entry written as a bare id list is matched by name.
157
+ *
158
+ * @param intent - The intent id: the file name without `.md`.
159
+ * @param name - The package name.
160
+ */
161
+ consumed(intent, name) {
162
+ return this.entries.some((entry) => entry.dir === void 0 && entry.name === name && entry.intents.includes(intent));
163
+ }
164
+ /**
165
+ * Whether an ATTRIBUTED entry (one that records a `dir`) for the project in
166
+ * `dir` consumed the intent, at any version. `dir` is normalised as pnpm
167
+ * normalises it (backslashes to `/`, leading `./` and trailing `/` removed).
168
+ *
169
+ * @param intent - The intent id: the file name without `.md`.
170
+ * @param dir - The project's workspace-relative directory.
171
+ */
172
+ consumedDir(intent, dir) {
173
+ const wanted = normalizeProjectDir(dir);
174
+ return this.entries.some((entry) => entry.dir !== void 0 && normalizeProjectDir(entry.dir) === wanted && entry.intents.includes(intent));
175
+ }
176
+ /**
177
+ * How the ledger records the intent against one project, as pnpm's
178
+ * `build_consumption_index` indexes it: an attributed entry counts for the
179
+ * project in its `dir`, a bare-list entry for the project its name resolves
180
+ * to (here, `project.name`). A version whose part before `+` contains `-` is
181
+ * a prerelease. `"stable"` when any matching entry is a stable version;
182
+ * otherwise `"prerelease-only"` when only prerelease entries list it;
183
+ * otherwise `"none"`.
184
+ *
185
+ * @param intent - The intent id: the file name without `.md`.
186
+ * @param project - The project's package name and workspace-relative directory.
187
+ */
188
+ consumption(intent, project) {
189
+ const wanted = normalizeProjectDir(project.dir);
190
+ let state = "none";
191
+ for (const entry of this.entries) {
192
+ if (!(entry.dir === void 0 ? entry.name === project.name : normalizeProjectDir(entry.dir) === wanted) || !entry.intents.includes(intent)) continue;
193
+ if (!isPrerelease(entry.version)) return "stable";
194
+ state = "prerelease-only";
195
+ }
196
+ return state;
197
+ }
198
+ };
199
+
200
+ export { Ledger, LedgerEntry, normalizeProjectDir };
@@ -1,6 +1,7 @@
1
1
  import { ReleaseType } from "./BumpType.js";
2
2
  import { ChangesetFile } from "./ChangesetFile.js";
3
3
  import { ChangesetParseError } from "./errors.js";
4
+ import { normalizeProjectDir } from "./Ledger.js";
4
5
  import { Effect, FileSystem, Path, PlatformError, Result, Schema } from "effect";
5
6
  import { readFileSync, readdirSync } from "node:fs";
6
7
 
@@ -30,6 +31,31 @@ var PendingChangeset = class extends Schema.Class("PendingChangeset")({
30
31
  return this.file.replace(/\.md$/, "");
31
32
  }
32
33
  };
34
+ /** The project a release key names, or `undefined` when it names none or several. */
35
+ const resolveProject = (key, packages) => {
36
+ const found = key.startsWith("./") ? packages.filter((pkg) => normalizeProjectDir(pkg.relativePath) === normalizeProjectDir(key)) : packages.filter((pkg) => pkg.name === key);
37
+ return found.length === 1 ? found[0] : void 0;
38
+ };
39
+ const filterByConsumption = (changesets, ledger, packages, keep) => {
40
+ const out = [];
41
+ for (const changeset of changesets) {
42
+ const id = changeset.id;
43
+ const releases = new Map([...changeset.releases].filter(([key]) => {
44
+ const project = resolveProject(key, packages);
45
+ return keep(project === void 0 ? "none" : ledger.consumption(id, {
46
+ name: project.name,
47
+ dir: project.relativePath
48
+ }));
49
+ }));
50
+ if (releases.size === 0) continue;
51
+ out.push(releases.size === changeset.releases.size ? changeset : PendingChangeset.make({
52
+ file: changeset.file,
53
+ releases,
54
+ summary: changeset.summary
55
+ }));
56
+ }
57
+ return out;
58
+ };
33
59
  /** The directory, under `.changeset/`, holding the changesets a pre-release consumed. */
34
60
  const PRE = "pre";
35
61
  const CONTEXT_FILES = /* @__PURE__ */ new Set([
@@ -139,6 +165,48 @@ var PendingChangesets = class {
139
165
  return yield* Effect.forEach(files, (file) => fs.readFileString(path.join(dir, file)).pipe(Effect.flatMap((text) => Effect.fromResult(toPending(file, text)))));
140
166
  });
141
167
  /**
168
+ * The changesets still pending under pnpm's versioning, given its
169
+ * {@link Ledger}: pnpm leaves an intent file in place until every project
170
+ * it names has released, so each release key is dropped when the ledger
171
+ * records its project as having consumed this intent, and a changeset with
172
+ * no key left is dropped. The project is resolved as pnpm resolves it: a
173
+ * key starting `./` names a directory (normalised), any other key a package
174
+ * name that must resolve to exactly one of `packages`; a key that resolves
175
+ * to none, or to several, is kept, as pnpm's `is_release_consumed` keeps it,
176
+ * for the planner to refuse. Consumption is read through
177
+ * {@link Ledger.consumption}, matching an attributed entry by `dir` and a
178
+ * bare-list entry by name.
179
+ *
180
+ * A prerelease-only consumption (the intent listed only against a version
181
+ * such as `2.1.0-alpha.0`) also drops the key, since pnpm's
182
+ * `collect_pending_intents` (`plan/propagation.rs`) excludes every id in
183
+ * `all_ids`. pnpm still counts such an intent toward the project's stable
184
+ * bump and changelog at graduation (`collect_lane_consumed_intents`, same
185
+ * file); {@link PendingChangesets.laneConsumed} returns that set.
186
+ *
187
+ * @param changesets - The changesets {@link PendingChangesets.read} returned.
188
+ * @param ledger - The ledger to read consumption from.
189
+ * @param packages - The workspace packages, to resolve a key to a project.
190
+ */
191
+ static unconsumed(changesets, ledger, packages) {
192
+ return filterByConsumption(changesets, ledger, packages, (state) => state === "none");
193
+ }
194
+ /**
195
+ * The changesets, narrowed to the release keys whose project has consumed
196
+ * the intent ONLY at prerelease versions: pnpm's
197
+ * `collect_lane_consumed_intents` (`plan/propagation.rs`). They are not
198
+ * pending, but still count toward the project's cumulative bump and the
199
+ * stable changelog when it graduates. Keys are resolved as in
200
+ * {@link PendingChangesets.unconsumed}.
201
+ *
202
+ * @param changesets - The changesets {@link PendingChangesets.read} returned.
203
+ * @param ledger - The ledger to read consumption from.
204
+ * @param packages - The workspace packages, to resolve a key to a project.
205
+ */
206
+ static laneConsumed(changesets, ledger, packages) {
207
+ return filterByConsumption(changesets, ledger, packages, (state) => state === "prerelease-only");
208
+ }
209
+ /**
142
210
  * Read the same files as {@link PendingChangesets.read}, in the same order,
143
211
  * but skip a file that does not read or parse and report it in `failures`
144
212
  * rather than failing the whole read. For a best-effort view of pending
@@ -0,0 +1,50 @@
1
+ import { Context, Effect, Layer, Option } from "effect";
2
+ import { NpmRegistry } from "@effected/npm";
3
+
4
+ // src/RegistryVersions.ts
5
+ /**
6
+ * The registry seam of first releases: is a project's manifest version
7
+ * already published?
8
+ *
9
+ * @remarks
10
+ * pnpm decides a first release by probing the registry for exactly the
11
+ * manifest version (`package.versions.contains_key(current)`,
12
+ * `crates/cli/src/cli_args/changelog.rs:322`), where only a 404 means
13
+ * unpublished and any other failure propagates. {@link ReleasePlan.read} asks
14
+ * this service for each public release when it is provided, and plans without
15
+ * it, treating nothing as a first release, when it is not.
16
+ *
17
+ * A project that renames itself with `publishConfig.name` is probed under
18
+ * that name, as pnpm does, so `ReleasePlan.read` passes the published name.
19
+ *
20
+ * @public
21
+ */
22
+ var RegistryVersions = class RegistryVersions extends Context.Service()("@effected/changesets/RegistryVersions") {
23
+ /**
24
+ * The service over `NpmRegistry`, each package read from the registry and
25
+ * with the credential `config` routes it to.
26
+ *
27
+ * @remarks
28
+ * `NpmConfig.targetFor(name)` picks the package's own registry (`@scope:registry`)
29
+ * and the credential npm would send for it, as pnpm's `registry_for` and
30
+ * `auth_header_for_package` do (`changelog.rs:298-308`). Reading the default
31
+ * registry anonymously instead would answer 404 for a scoped package on a
32
+ * private registry, which reads as unpublished and debuts a version that
33
+ * exists.
34
+ *
35
+ * A parameterized layer factory mints a fresh reference per call and layers
36
+ * memoize by reference: bind the result to a `const` once, or the layer
37
+ * builds twice.
38
+ *
39
+ * @param config - The resolved npm configuration, usually `NpmConfig.load`'s.
40
+ */
41
+ static layerFrom = (config) => Layer.effect(RegistryVersions, Effect.gen(function* () {
42
+ const registry = yield* NpmRegistry;
43
+ return { published: Effect.fn("RegistryVersions.published")(function* (name, version) {
44
+ const versions = yield* registry.versions(name, config.targetFor(name));
45
+ return Option.isSome(versions) && versions.value.includes(version);
46
+ }) };
47
+ }));
48
+ };
49
+
50
+ export { RegistryVersions };
@@ -0,0 +1,30 @@
1
+ import { Schema } from "effect";
2
+
3
+ // src/ReleaseCause.ts
4
+ /**
5
+ * Why a release is in a plan, pnpm's `ReleaseCause`
6
+ * (`crates/versioning/src/plan.rs:56-68`): `intent`, a changeset naming it;
7
+ * `dependencies`, a dependency it ripples from; `fixed`, a fixed group it
8
+ * belongs to; `epic`, its epic lead crossing a major. The literals are listed
9
+ * in pnpm's report order, the derived `Ord`, which is alphabetical.
10
+ *
11
+ * @public
12
+ */
13
+ const ReleaseCause = Schema.Literals([
14
+ "dependencies",
15
+ "epic",
16
+ "fixed",
17
+ "intent"
18
+ ]);
19
+ /**
20
+ * Causes in pnpm's report order, each once: the order of
21
+ * `ReleaseCause.literals`, so the schema is the one source of it.
22
+ *
23
+ * @internal
24
+ */
25
+ const sortCauses = (causes) => {
26
+ const present = new Set(causes);
27
+ return ReleaseCause.literals.filter((cause) => present.has(cause));
28
+ };
29
+
30
+ export { ReleaseCause, sortCauses };
package/ReleaseEdits.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { MissingPackageError } from "./errors.js";
2
+ import { twinReleases } from "./internal/twins.js";
2
3
  import { DEPENDENCY_KINDS, WORKSPACE, cleanVersion, increment, matchNames, parseRange, satisfies, shouldUpdate, writtenSets } from "./internal/versions.js";
3
4
  import { PreState } from "./PreState.js";
4
5
  import { InvalidVersionError, SemVer } from "@effected/semver";
@@ -163,6 +164,8 @@ const rangeEdits = (pkg, releases, options, pathOf) => {
163
164
  * @internal
164
165
  */
165
166
  const computeEdits = (plan, input) => {
167
+ const twins = twinReleases(plan.releases);
168
+ if (twins !== void 0) return Result.fail(twins);
166
169
  try {
167
170
  return Result.succeed(editsOrHalt(plan, input));
168
171
  } catch (error) {
@@ -0,0 +1,49 @@
1
+ import { Effect, FileSystem, Option, Path, Result, Schema } from "effect";
2
+ import { PnpmSettings } from "@effected/pnpm";
3
+
4
+ // src/ReleaseManager.ts
5
+ const detect = Effect.fn("ReleaseManager.detect")(function* (root, options) {
6
+ const fs = yield* FileSystem.FileSystem;
7
+ const path = yield* Path.Path;
8
+ const settings = yield* PnpmSettings.load({
9
+ cwd: root,
10
+ env: options?.env ?? {},
11
+ platform: options?.platform ?? "linux"
12
+ });
13
+ if (yield* Effect.fromResult(Result.map(settings.versioning(), Option.isSome))) return "pnpm";
14
+ return (yield* fs.exists(path.join(root, ".changeset", "ledger.yaml"))) ? "pnpm" : "changesets";
15
+ });
16
+ /**
17
+ * The tool that plans and applies a repository's releases: the Changesets
18
+ * CLI, or pnpm's own versioning.
19
+ *
20
+ * @remarks
21
+ * `detect` answers `"pnpm"` when the workspace's `pnpm-workspace.yaml` has a
22
+ * `versioning` block, or `.changeset/ledger.yaml` exists, and `"changesets"`
23
+ * otherwise. pnpm ignores `.changeset/pre.json` and `config.json` entirely, so
24
+ * their presence decides nothing: a `pre.json` beside a `versioning` key is
25
+ * still pnpm. A `versioning` block that does not decode fails with
26
+ * `PnpmSettingsError` rather than reading as absent. The value is both the
27
+ * schema of the two names and the namespace of `detect`.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { Effect } from "effect";
32
+ * import { ReleaseManager } from "@effected/changesets";
33
+ *
34
+ * // `FileSystem` and `Path` come from the platform layer at the edge.
35
+ * const program = ReleaseManager.detect("/repo").pipe(Effect.map((manager) => manager === "pnpm"));
36
+ * ```
37
+ *
38
+ * @public
39
+ */
40
+ const ReleaseManager = Object.assign(Schema.Literals(["changesets", "pnpm"]), {
41
+ /**
42
+ * Detect which tool plans the releases of the repository at `root`.
43
+ *
44
+ * @param root - The repository root, where `pnpm-workspace.yaml` and `.changeset/` live.
45
+ * @param options - The environment handed to `PnpmSettings.load`; see {@link ReleaseManagerDetectOptions}.
46
+ */
47
+ detect });
48
+
49
+ export { ReleaseManager };