@effected/changesets 0.2.0 → 0.4.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/ReleasePlan.js CHANGED
@@ -1,20 +1,15 @@
1
1
  import { ChangesetConfig } from "./ChangesetConfig.js";
2
- import { ChangesetConfigError, UnknownPackageError } from "./errors.js";
2
+ import { ChangesetConfigError, SnapshotPreModeError, SnapshotTemplateError, UnknownPackageError } from "./errors.js";
3
+ import { DEPENDENCY_KINDS, WORKSPACE, cleanVersion, increment, matchNames, parseRange, satisfies } from "./internal/versions.js";
3
4
  import { PendingChangeset, PendingChangesets } from "./PendingChangesets.js";
4
5
  import { PreState } from "./PreState.js";
6
+ import { computeEdits } from "./ReleaseEdits.js";
5
7
  import { Effect, FileSystem, Option, Path, Result, Schema } from "effect";
6
8
  import { posix } from "node:path";
7
- import { GlobPattern } from "@effected/glob";
8
9
  import { InvalidVersionError, Range, SemVer } from "@effected/semver";
9
10
  import { WorkspaceDiscovery, WorkspaceDiscoveryError, WorkspacePackage } from "@effected/workspaces";
10
11
 
11
12
  // src/ReleasePlan.ts
12
- const DEPENDENCY_KINDS = [
13
- "dependencies",
14
- "devDependencies",
15
- "peerDependencies",
16
- "optionalDependencies"
17
- ];
18
13
  const RANK = {
19
14
  none: 0,
20
15
  patch: 1,
@@ -28,28 +23,50 @@ var Halt = class {
28
23
  this.failure = failure;
29
24
  }
30
25
  };
26
+ /** The placeholders in the order the oracle fills them, each pass over the previous one's output. */
27
+ const PLACEHOLDERS = [
28
+ "commit",
29
+ "commit-short",
30
+ "tag",
31
+ "timestamp",
32
+ "datetime"
33
+ ];
31
34
  /**
32
- * A package version as node-semver reads one without `loose`: surrounding
33
- * whitespace and a single leading `v` are dropped, so `v1.0.0` is `1.0.0`. Any
34
- * other prefix, `=1.2.0` among them, stays and fails to parse.
35
+ * `@changesets/assemble-release-plan`'s `getSnapshotSuffix`, with the clock
36
+ * read replaced by `snapshot.timestamp`. `tag` and `commit` arrive with `""`
37
+ * already turned into `undefined`.
35
38
  */
36
- const cleanVersion = (version) => {
37
- const trimmed = version.trim();
38
- return trimmed.startsWith("v") ? trimmed.slice(1) : trimmed;
39
+ const snapshotSuffix = (template, tag, commit, timestamp) => {
40
+ const values = {
41
+ commit,
42
+ "commit-short": commit?.slice(0, 7),
43
+ tag,
44
+ timestamp: timestamp.getTime().toString(),
45
+ datetime: timestamp.toISOString().replace(/\.\d{3}Z$/, "").replace(/[^\d]/g, "")
46
+ };
47
+ if (template === void 0 || template === "") return [values.tag, values.datetime].filter(Boolean).join("-");
48
+ if (!template.includes("{tag}") && tag !== void 0) throw new Halt(new SnapshotTemplateError({
49
+ template,
50
+ placeholder: "tag",
51
+ kind: "missingPlaceholder"
52
+ }));
53
+ let filled = template;
54
+ for (const key of PLACEHOLDERS) filled = filled.replaceAll(`{${key}}`, () => {
55
+ const value = values[key];
56
+ if (value === void 0) throw new Halt(new SnapshotTemplateError({
57
+ template,
58
+ placeholder: key,
59
+ kind: "missingValue"
60
+ }));
61
+ return value;
62
+ });
63
+ return filled;
39
64
  };
40
65
  const parseVersion = (version) => {
41
66
  const parsed = SemVer.parseResult(cleanVersion(version));
42
67
  if (Result.isFailure(parsed)) throw new Halt(parsed.failure);
43
68
  return parsed.success;
44
69
  };
45
- const WORKSPACE = /^workspace:/;
46
- /** A range, also as node-semver reads a `v` before a version in one: `^v1.0.0` is `^1.0.0`. */
47
- const parseRange = (specifier) => {
48
- if (specifier.includes(":")) return void 0;
49
- const parsed = Range.parseResult(specifier);
50
- if (Result.isSuccess(parsed)) return parsed.success;
51
- return Result.getOrUndefined(Range.parseResult(specifier.replace(/(^|[\s^~<>=])v(?=\d)/g, "$1")));
52
- };
53
70
  const pointsAt = (specifier, dependency) => posix.normalize(specifier) === dependency.relativePath;
54
71
  /** The specifier that decides an edge: the last kind naming the dependency, link and file devDependencies aside. */
55
72
  const edgeSpecifiers = (dependent) => {
@@ -100,38 +117,6 @@ const declaredRanges = (dependent, dependency, rawOldVersion) => {
100
117
  }
101
118
  return ranges;
102
119
  };
103
- const satisfies = (version, specifier) => {
104
- const range = parseRange(specifier);
105
- const parsed = Result.getOrUndefined(SemVer.parseResult(cleanVersion(version)));
106
- return range !== void 0 && parsed !== void 0 && Range.satisfies(parsed, range);
107
- };
108
- /**
109
- * `semver.inc`'s rule, which `SemVerBump` deliberately does not follow: a bump
110
- * a prerelease is already heading for completes it rather than incrementing.
111
- */
112
- const increment = (version, type) => {
113
- return version.prerelease.length > 0 && (type === "patch" || version.patch === 0 && (type === "minor" || version.minor === 0)) ? SemVer.truncate(version, "prerelease") : version.bump[type]();
114
- };
115
- /** The workspace's names a list of globs selects, `!` negation applying in order, in workspace order. */
116
- const matchNames = (packages, patterns) => {
117
- const matchers = patterns.map((source) => {
118
- const negated = source.startsWith("!");
119
- const glob = negated ? source.slice(1) : source;
120
- const compiled = Result.getOrUndefined(GlobPattern.compileResult(glob));
121
- return {
122
- negated,
123
- matches: (name) => compiled?.matches(name) ?? name === glob
124
- };
125
- });
126
- const selected = [];
127
- for (const { name } of packages) {
128
- let passed = false;
129
- for (const { negated, matches } of matchers) if (!passed && !negated && matches(name)) passed = true;
130
- else if (passed && negated && matches(name)) passed = false;
131
- if (passed) selected.push(name);
132
- }
133
- return selected;
134
- };
135
120
  /** The configuration errors `@changesets/config` rejects a fixed or linked group for. */
136
121
  const groupError = (fixed, linked) => {
137
122
  for (const [kind, groups] of [["fixed", fixed], ["linked", linked]]) {
@@ -160,10 +145,21 @@ const LoneManifest = Schema.Struct({
160
145
  version: Schema.optionalKey(Schema.String),
161
146
  private: Schema.optionalKey(Schema.Boolean)
162
147
  });
163
- /** The package of a repository with no workspace file, which discovery has no root for. */
164
- const readLonePackage = Effect.fnUntraced(function* (root, notFound) {
148
+ /**
149
+ * The package of a repository with no workspace file, which discovery has no
150
+ * root for: the nearest `package.json` at or above `directory`, where the
151
+ * oracle's `@manypkg/find-root` falls back to when it finds no monorepo.
152
+ */
153
+ const readLonePackage = Effect.fnUntraced(function* (directory, notFound) {
165
154
  const fs = yield* FileSystem.FileSystem;
166
- const packageJsonPath = (yield* Path.Path).join(root, "package.json");
155
+ const path = yield* Path.Path;
156
+ let root = path.resolve(directory);
157
+ while (!(yield* fs.exists(path.join(root, "package.json")))) {
158
+ const parent = path.dirname(root);
159
+ if (parent === root) return yield* Effect.fail(notFound);
160
+ root = parent;
161
+ }
162
+ const packageJsonPath = path.join(root, "package.json");
167
163
  const text = yield* fs.readFileString(packageJsonPath).pipe(Effect.catch((error) => error.reason._tag === "NotFound" ? Effect.fail(notFound) : Effect.fail(error)));
168
164
  const invalid = (kind) => (cause) => new WorkspaceDiscoveryError({
169
165
  root,
@@ -181,7 +177,8 @@ const readLonePackage = Effect.fnUntraced(function* (root, notFound) {
181
177
  path: root,
182
178
  packageJsonPath,
183
179
  relativePath: ".",
184
- workspaceRoot: root
180
+ workspaceRoot: root,
181
+ manifestRecord: json
185
182
  })];
186
183
  });
187
184
  /**
@@ -206,7 +203,46 @@ var PlannedRelease = class extends Schema.Class("PlannedRelease")({
206
203
  oldVersion: Schema.String,
207
204
  /** The version after the release; equal to `oldVersion` when `type` is `none`. */
208
205
  newVersion: Schema.String,
209
- /** The changeset files naming the package; empty for a package reached only as a dependent. */
206
+ /**
207
+ * The ids of the changesets in the plan that name the package, as the
208
+ * oracle lists them: each {@link PendingChangeset.id}, the file name
209
+ * without `.md` (`pre/<name>` for one an earlier pre-release consumed).
210
+ * The plan's own `changesets` holds the changesets themselves.
211
+ *
212
+ * @remarks
213
+ * An empty list always means the package's bump does not come from a
214
+ * changeset of its own in this plan. It is reached as a dependent, pulled
215
+ * into a `fixed` group, or completed from a prerelease on `exit`. The
216
+ * converse does not hold: a non-empty list does not mean the package's own
217
+ * changeset set its bump. Every path that builds a release:
218
+ *
219
+ * - A changeset naming the package, `none` included, lists its id. A
220
+ * package named only `none` keeps the id while it stays `none`.
221
+ * - A ripple into a package not yet in the plan, or into a `none` entry,
222
+ * replaces it with a new release whose list is empty. So a package one
223
+ * changeset named `none` and a dependency then bumped has an empty list,
224
+ * as the oracle answers (`explicit-none-rippled`). A ripple never
225
+ * touches a package already releasing.
226
+ * - A `fixed` group adds a missing member with an empty list, and raises
227
+ * an existing member's type, including a `none` entry's, keeping its
228
+ * list. A raised member can therefore list only a changeset that named
229
+ * it `none`, or a smaller bump than the type it ends with.
230
+ * - A `linked` group raises only members already releasing and keeps
231
+ * their lists.
232
+ * - On `exit`, a package still on a numbered prerelease that is not in
233
+ * the plan is added `patch` with an empty list. A `none` entry is raised
234
+ * to `patch` and keeps its list.
235
+ * - In pre mode the changesets an earlier pre-release consumed are not in
236
+ * the plan. So the list names only this pre-release's new changesets,
237
+ * and a package whose own changesets were all consumed, and which a
238
+ * ripple brings back, has an empty list.
239
+ * - A snapshot plan builds its releases exactly as a plain one does.
240
+ *
241
+ * To tell a group or exit bump from a ripple, read `fixed` and `linked`
242
+ * and the plan's `preState`. To tell whether the package's own changeset
243
+ * set its type, compare `type` with the highest bump its listed changesets
244
+ * give it.
245
+ */
210
246
  changesets: Schema.Array(Schema.String)
211
247
  }) {};
212
248
  /**
@@ -275,6 +311,13 @@ var PlannedRelease = class extends Schema.Class("PlannedRelease")({
275
311
  * again, no suffix is added, and every package whose version carries a
276
312
  * numbered prerelease bumps at least `patch`; those added bumps reach no
277
313
  * dependent.
314
+ * - A snapshot plan (`changeset version --snapshot`, whose oracle is
315
+ * `@changesets/assemble-release-plan`'s snapshot argument) plans the same
316
+ * releases and only rewrites each bumped `newVersion` to
317
+ * `<base>-<suffix>`. `<base>` is `0.0.0`, or with `useCalculatedVersion` the
318
+ * version the plan would otherwise give. A `none` entry keeps its version,
319
+ * and dependents are still checked against the calculated version, not the
320
+ * snapshot one. {@link ReleasePlan.assemble} has the suffix rules.
278
321
  *
279
322
  * Deliberate differences, each ruled:
280
323
  *
@@ -285,6 +328,10 @@ var PlannedRelease = class extends Schema.Class("PlannedRelease")({
285
328
  * - A prerelease number that is not a number, such as `1.0.0-next.x`, fails
286
329
  * with `InvalidVersionError` in pre-release mode; the oracle throws an
287
330
  * internal error.
331
+ * - A Ruby-style `~>` range (`~>1.0.0`), which node-semver reads as `~`,
332
+ * is not a range here: `@effected/semver` rejects it. It draws no edge,
333
+ * so it never ripples, where the oracle bumps the dependent once the
334
+ * range is left, and {@link ReleasePlan.edits} never rewrites it.
288
335
  * - A version changesets cannot bump, such as `=1.2.0`, which npm's loose
289
336
  * parse reads but strict `semver.inc` does not, fails with
290
337
  * `InvalidVersionError` wherever it must be read. The oracle crashes on it
@@ -301,13 +348,12 @@ var PlannedRelease = class extends Schema.Class("PlannedRelease")({
301
348
  * types and changeset ids here are its later plans', so in exit mode a
302
349
  * consumed changeset is named `pre/<file>`, where the oracle moved it,
303
350
  * though it was never moved.
304
- * - Snapshot versions are not planned. `@changesets/get-release-plan` takes no
305
- * snapshot input, so it cannot be the oracle for one, and a snapshot is a
306
- * flag on `changeset version`, not a state a repository is in.
351
+ * - An empty snapshot `tag` or `commit` is no value at all; see
352
+ * {@link ReleasePlan.assemble}.
307
353
  *
308
354
  * @public
309
355
  */
310
- var ReleasePlan = class ReleasePlan extends Schema.Class("ReleasePlan")({
356
+ var ReleasePlan = class extends Schema.Class("ReleasePlan")({
311
357
  /** The planned releases, sorted by package name. */
312
358
  releases: Schema.Array(PlannedRelease),
313
359
  /**
@@ -317,7 +363,13 @@ var ReleasePlan = class ReleasePlan extends Schema.Class("ReleasePlan")({
317
363
  */
318
364
  changesets: Schema.Array(PendingChangeset),
319
365
  /** The pre-release state the plan was made in, when the repository has one. */
320
- preState: Schema.optionalKey(PreState)
366
+ preState: Schema.optionalKey(PreState),
367
+ /**
368
+ * Whether this is a snapshot release's plan, made with a `snapshot` input.
369
+ * {@link ReleasePlan.edits} reads it: a snapshot pins dependents exactly
370
+ * and leaves an `exit`-mode `pre.json` in place.
371
+ */
372
+ snapshot: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false)), Schema.withConstructorDefault(Effect.succeed(false)))
321
373
  }) {
322
374
  /**
323
375
  * Assemble the plan from packages, changesets and a config, with no IO.
@@ -330,14 +382,54 @@ var ReleasePlan = class ReleasePlan extends Schema.Class("ReleasePlan")({
330
382
  * fixed or linked member; and with
331
383
  * {@link ChangesetConfigError}
332
384
  * when a package is in two fixed groups, two linked groups, or a group of
333
- * each. What the oracle rejects outright and this does not check is planned,
385
+ * each. A snapshot adds {@link SnapshotPreModeError} and
386
+ * {@link SnapshotTemplateError}, described below. What the oracle rejects outright and this does not check is planned,
334
387
  * not refused: a changeset mixing skipped and released packages, a public
335
388
  * package depending on a skipped one, and `privatePackages` with `tag` on
336
389
  * and `version` off.
337
390
  *
391
+ * With `snapshot`, the plan is a snapshot release's, matching
392
+ * `@changesets/assemble-release-plan` given the same snapshot argument:
393
+ *
394
+ * - It fails {@link SnapshotPreModeError} when `pre` is in `pre` mode.
395
+ * The oracle itself plans one; the refusal is `changeset version`'s,
396
+ * which never reaches the oracle. In `exit` mode a snapshot is planned.
397
+ * - `useCalculatedVersion` and `prereleaseTemplate` come from
398
+ * `config.snapshot` unless the snapshot overrides them. An empty
399
+ * `prereleaseTemplate` override is the default suffix, as an empty
400
+ * `--snapshot-prerelease-template` is.
401
+ * - With no template the suffix is `<tag>-<datetime>`, or `<datetime>`
402
+ * with no tag. A template may use `{tag}`, `{commit}`,
403
+ * `{commit-short}` (its first seven characters), `{timestamp}` (epoch
404
+ * milliseconds) and `{datetime}` (`YYYYMMDDHHmmss`, UTC), all taken from
405
+ * `snapshot.timestamp`, never the clock. It fails
406
+ * {@link SnapshotTemplateError} when it uses `{tag}`, `{commit}` or
407
+ * `{commit-short}` with no value, or omits `{tag}` while a tag is given.
408
+ * Placeholders are filled in that order, each over the last one's
409
+ * output, as the oracle fills them.
410
+ * - The suffix is not checked as semver, any more than the oracle checks
411
+ * it: `--snapshot pr#123` gives `0.0.0-pr#123-<datetime>`.
412
+ * - An invalid `timestamp` Date throws `RangeError`, as
413
+ * `Date.prototype.toISOString` does: it is a programmer error, not a
414
+ * planning failure.
415
+ *
416
+ * An empty `tag` or `commit` is treated as absent.
417
+ * `changeset version --snapshot` never passes `""` to the oracle: an empty `--snapshot` value
418
+ * is falsy there, so it plans no snapshot at all, and a bare `--snapshot`
419
+ * passes no tag. Called directly with `tag: ""`, the oracle fills `{tag}`
420
+ * with nothing and refuses a template without `{tag}`, while
421
+ * `@changesets/apply-release-plan` reads the same `""` as "not a snapshot"
422
+ * and writes caret ranges. With no template the two readings give the same
423
+ * version; with one, this follows the bare `--snapshot` reading, so a
424
+ * template with `{tag}` fails `missingValue` and one without it succeeds.
425
+ * Because every value that can fill a placeholder is then non-empty, the
426
+ * suffix is never empty, so the oracle's quiet fallback to plain versions
427
+ * on an empty suffix cannot happen here.
428
+ *
338
429
  * @param input - The packages to plan, the pending changesets, the config
339
- * and, in pre-release mode, the {@link PreState}. {@link ReleasePlan.read}
340
- * decides whether the workspace root is one of the packages.
430
+ * and, in pre-release mode, the {@link PreState}, and for a snapshot
431
+ * release the {@link ReleaseSnapshot}. {@link ReleasePlan.read} decides
432
+ * whether the workspace root is one of the packages.
341
433
  */
342
434
  static assemble(input) {
343
435
  try {
@@ -348,37 +440,186 @@ var ReleasePlan = class ReleasePlan extends Schema.Class("ReleasePlan")({
348
440
  }
349
441
  }
350
442
  /**
443
+ * What `changeset version` writes for `plan`, as data: each manifest's new
444
+ * `version` and rewritten dependency ranges, the changeset files it
445
+ * deletes or, in pre mode, moves under `.changeset/pre/`, and the
446
+ * `pre.json` it leaves. CHANGELOG files are not covered. Nothing is
447
+ * written; the caller applies the {@link ReleaseEdits}.
448
+ *
449
+ * `@changesets/apply-release-plan` is the oracle, and
450
+ * `__test__/ReleaseEdits.oracle.test.ts` compares it on disk. Its rules:
451
+ *
452
+ * - Every planned package's manifest gets its new `version`, and so does
453
+ * nothing else. Only planned packages and the workspace root (marked
454
+ * `isRootWorkspace` among `packages`) have their ranges rewritten: a
455
+ * package outside the plan keeps a range on a released dependency, even
456
+ * one the new version leaves.
457
+ * - A range on a released dependency (not a `none` entry) is rewritten in
458
+ * `dependencies`, `devDependencies`, `peerDependencies` and
459
+ * `optionalDependencies` alike when the new version leaves it, or, while
460
+ * it still holds, when the release's bump is at least
461
+ * `updateInternalDependencies`. A held `peerDependencies` range instead
462
+ * follows `onlyUpdatePeerDependentsWhenOutOfRange` (from the config's
463
+ * `extra`): rewritten unless it is on.
464
+ * - `workspace:*`, `workspace:^`, `workspace:~` and a `workspace:` path are
465
+ * never rewritten: they follow the dependency on their own. A
466
+ * `workspace:<range>` is rewritten and keeps its `workspace:` prefix.
467
+ * `file:`, `link:`, `catalog:`, `npm:` and any non-range specifier are
468
+ * never rewritten, and under `bumpVersionsWithWorkspaceProtocolOnly`
469
+ * neither is a plain range.
470
+ * - A range that matches every version (`*`, `x`, `>=0.0.0`, or a `||`
471
+ * with such a part) is rewritten only to a prerelease version.
472
+ * - The new range is the old one's leading operator (`^`, `~`, `>=`, `<=`,
473
+ * `>`, or none) before the new version. A range of exactly two
474
+ * comparators written with both `>` and `<` becomes `>=<new>` with its
475
+ * upper bound kept while the new version satisfies it, else
476
+ * `<<new bumped again>>`, in the order it was written. In a snapshot
477
+ * plan every rewritten range is the exact new version.
478
+ * - Each changeset in the plan is deleted, or in pre mode moved to
479
+ * `pre/<file>`, unless it names a skipped package (ignored, private
480
+ * while `privatePackages.version` is off, or version-less), which leaves
481
+ * it in place.
482
+ * - `pre.json` is deleted in `exit` mode unless the plan is a snapshot,
483
+ * and otherwise left as it is.
484
+ * - A pre-release consumes a changeset by moving its file to
485
+ * `.changeset/pre/`, never by listing its id in `pre.json`: the current
486
+ * layout has no such list, so in pre mode `preState` is the plan's own,
487
+ * unchanged, and the consumed files are `moveChangesets`. That is the
488
+ * directory {@link PendingChangesets.read} reads back as `pre/<file>`.
489
+ *
490
+ * Deliberate differences, each ruled:
491
+ *
492
+ * - An edit that would write the value already there is left out, and so
493
+ * is a manifest with nothing to change; the oracle rewrites the same
494
+ * value. The files end the same.
495
+ * - The oracle only deletes a changeset file it finds on disk; the edits
496
+ * name every consumed changeset, since the plan was read from them. An
497
+ * older-layout `pre.json`'s listed changeset is named as the plan names
498
+ * it (`pre/<file>` in exit mode), where the oracle had moved it while
499
+ * reading; the file itself is still at `<file>`. Neither does this
500
+ * migrate that `pre.json`, which the oracle rewrites as it reads.
501
+ * - A `~>` range is never rewritten, where the oracle rewrites it as `~`:
502
+ * `@effected/semver` rejects the Ruby-style operator, so it is not a
503
+ * range here. It never ripples in {@link ReleasePlan.assemble} either.
504
+ * - `changeset version --snapshot ""` is a third state no plan here
505
+ * holds. The CLI plans no snapshot for an empty value, but hands the
506
+ * `""` to `apply-release-plan`, which then keeps an `exit`-mode
507
+ * `pre.json` (it deletes one only when the snapshot is `null`) while
508
+ * writing caret ranges. A plan without a snapshot deletes that
509
+ * `pre.json`; a caller reproducing the CLI keeps it.
510
+ *
511
+ * Fails with {@link MissingPackageError} when the plan releases a package
512
+ * `packages` lacks, and with `InvalidVersionError` when a bounded range
513
+ * must be bumped past a new version that is not a version, which a plan
514
+ * {@link ReleasePlan.assemble} made never has.
515
+ *
516
+ * @param plan - The plan to apply.
517
+ * @param input - Every package of the workspace, the root included, as
518
+ * `WorkspaceDiscovery.listPackagesIn` lists them, and the config the plan
519
+ * was made with.
520
+ */
521
+ static edits(plan, input) {
522
+ return computeEdits(plan, input);
523
+ }
524
+ /**
351
525
  * Discover the workspace's packages, read its config, pending changesets and
352
526
  * `.changeset/pre.json`, and {@link ReleasePlan.assemble | assemble} the
353
- * plan.
527
+ * plan. {@link ReleasePlan.readWithContext} reads the same plan and also
528
+ * returns the packages and config it was made from.
354
529
  *
355
- * `root` decides all three, whatever directory the `WorkspaceDiscovery` layer
356
- * was built from. The workspace root package is left out while other packages
357
- * exist. When there are none it is the package and is planned, including when
358
- * `root` has only a `package.json` and no workspace file. The oracle refuses
359
- * `packages: []` and patterns that match nothing; here they plan the root too,
360
- * because discovery reports them the same way. A root listed in `packages:`
530
+ * `directory` may be the workspace root or any directory inside it: the
531
+ * root is found by climbing, as `@changesets/get-release-plan` climbs, to
532
+ * the nearest workspace root, or with none to the nearest `package.json`.
533
+ * That root decides the config, the changesets and `pre.json`, whatever
534
+ * directory the `WorkspaceDiscovery` layer was built from. The workspace
535
+ * root package is left out while other packages exist. When there are
536
+ * none it is the package and is planned, including when the root has only
537
+ * a `package.json` and no workspace file. The oracle refuses `packages: []`
538
+ * and patterns that match nothing; here they plan the root too, because
539
+ * discovery reports them the same way. A root listed in `packages:`
361
540
  * alongside others stays out, where the oracle plans it. A root with a
362
- * catalog-only workspace file answers for itself, where the oracle climbs to
363
- * any enclosing workspace.
541
+ * catalog-only workspace file answers for itself, where the oracle climbs
542
+ * to any enclosing workspace.
543
+ *
544
+ * `WorkspaceDiscovery` memoizes each root's packages for the layer's
545
+ * lifetime. A long-lived host that plans again after applying a release
546
+ * calls `WorkspaceDiscovery`'s `refreshIn(root)` first, or the new plan
547
+ * reads the versions the release replaced.
364
548
  *
365
- * @param root - The repository root.
549
+ * @param directory - The workspace root, or a directory inside it.
550
+ * @param options - `snapshot` plans a snapshot release, as
551
+ * {@link ReleasePlan.assemble} describes.
366
552
  */
367
- static read = Effect.fn("ReleasePlan.read")(function* (root) {
368
- const discovered = yield* (yield* WorkspaceDiscovery).listPackagesIn(root).pipe(Effect.catchTag("WorkspaceRootNotFoundError", (error) => readLonePackage(root, error)));
369
- const config = yield* ChangesetConfig.read(root);
370
- const changesets = yield* PendingChangesets.read(root);
371
- const pre = yield* PreState.read(root);
372
- const members = discovered.filter((pkg) => !pkg.isRootWorkspace);
373
- const packages = members.length > 0 ? members : discovered;
374
- return yield* Effect.fromResult(ReleasePlan.assemble({
375
- packages,
376
- changesets,
377
- config,
378
- ...Option.isSome(pre) ? { pre: pre.value } : {}
379
- }));
553
+ static read = Effect.fn("ReleasePlan.read")(function* (directory, options) {
554
+ return (yield* readContext(directory, options)).plan;
555
+ });
556
+ /**
557
+ * {@link ReleasePlan.read}, returning the plan with everything it was read
558
+ * from, so a caller hands {@link ReleasePlan.edits} and `Changelog.entry`
559
+ * exactly the packages and config the plan was made with instead of
560
+ * discovering them again.
561
+ *
562
+ * @param directory - The workspace root, or a directory inside it.
563
+ * @param options - `snapshot` plans a snapshot release, as
564
+ * {@link ReleasePlan.assemble} describes.
565
+ * @returns a {@link ReleaseContext}. It fails as {@link ReleasePlan.read} does.
566
+ */
567
+ static readWithContext = Effect.fn("ReleasePlan.readWithContext")(function* (directory, options) {
568
+ return yield* readContext(directory, options);
380
569
  });
381
570
  };
571
+ /**
572
+ * A {@link ReleasePlan} with what {@link ReleasePlan.readWithContext} read it
573
+ * from.
574
+ *
575
+ * @example
576
+ * ```ts
577
+ * import { ReleasePlan } from "@effected/changesets";
578
+ * import { Effect } from "effect";
579
+ *
580
+ * const program = Effect.gen(function* () {
581
+ * const { plan, packages, config } = yield* ReleasePlan.readWithContext("/repo/packages/a");
582
+ * return yield* Effect.fromResult(ReleasePlan.edits(plan, { packages, config }));
583
+ * });
584
+ * ```
585
+ *
586
+ * @public
587
+ */
588
+ var ReleaseContext = class extends Schema.Class("ReleaseContext")({
589
+ /** The workspace root the plan was read from: the directory climbed to, not the one given. */
590
+ root: Schema.String,
591
+ /** The plan. */
592
+ plan: ReleasePlan,
593
+ /**
594
+ * Every package of the workspace, the root included, as
595
+ * {@link ReleasePlan.edits} and `Changelog.entry` take them. For a
596
+ * repository with no workspace file it is the one root package.
597
+ */
598
+ packages: Schema.Array(WorkspacePackage),
599
+ /** The config the plan was made with. */
600
+ config: ChangesetConfig
601
+ }) {};
602
+ const readContext = Effect.fnUntraced(function* (directory, options) {
603
+ const discovered = yield* (yield* WorkspaceDiscovery).listPackagesIn(directory).pipe(Effect.catchTag("WorkspaceRootNotFoundError", (error) => readLonePackage(directory, error)));
604
+ const root = discovered[0]?.workspaceRoot ?? directory;
605
+ const config = yield* ChangesetConfig.read(root);
606
+ const changesets = yield* PendingChangesets.read(root);
607
+ const pre = yield* PreState.read(root);
608
+ const members = discovered.filter((pkg) => !pkg.isRootWorkspace);
609
+ const plan = yield* Effect.fromResult(ReleasePlan.assemble({
610
+ packages: members.length > 0 ? members : discovered,
611
+ changesets,
612
+ config,
613
+ ...Option.isSome(pre) ? { pre: pre.value } : {},
614
+ ...options?.snapshot === void 0 ? {} : { snapshot: options.snapshot }
615
+ }));
616
+ return ReleaseContext.make({
617
+ root,
618
+ plan,
619
+ packages: discovered,
620
+ config
621
+ });
622
+ });
382
623
  /** The highest of `types`, none of which is `none`. */
383
624
  const highestType = (types) => types.reduce((high, type) => RANK[type] > RANK[high] ? type : high, "none");
384
625
  /**
@@ -387,7 +628,8 @@ const highestType = (types) => types.reduce((high, type) => RANK[type] > RANK[hi
387
628
  * linked groups in step until none of the three changes anything.
388
629
  */
389
630
  const assembleOrHalt = (input) => {
390
- const { packages, changesets, config, pre } = input;
631
+ const { packages, changesets, config, pre, snapshot } = input;
632
+ if (snapshot !== void 0 && pre?.mode === "pre") throw new Halt(new SnapshotPreModeError({ preTag: pre.tag }));
391
633
  const byName = new Map(packages.map((pkg) => [pkg.name, pkg]));
392
634
  const ignored = new Set(matchNames(packages, config.ignore));
393
635
  const isSkipped = (pkg) => ignored.has(pkg.name) || pkg.private && !config.privatePackages.version || pkg.version === void 0;
@@ -432,12 +674,12 @@ const assembleOrHalt = (input) => {
432
674
  name,
433
675
  type,
434
676
  oldVersion: pkg.version,
435
- changesets: [changeset.file]
677
+ changesets: [changeset.id]
436
678
  });
437
679
  continue;
438
680
  }
439
681
  if (RANK[type] > RANK[release.type]) release.type = type;
440
- release.changesets.push(changeset.file);
682
+ release.changesets.push(changeset.id);
441
683
  }
442
684
  const alwaysRipple = unsafeOption(config, "updateInternalDependents") === "always";
443
685
  const dependents = dependentsByName(packages, config.extra.bumpVersionsWithWorkspaceProtocolOnly === true);
@@ -564,9 +806,15 @@ const assembleOrHalt = (input) => {
564
806
  });
565
807
  else if (release.type === "none") release.type = "patch";
566
808
  }
809
+ const suffix = snapshot === void 0 ? void 0 : snapshotSuffix(snapshot.prereleaseTemplate ?? config.snapshot.prereleaseTemplate, snapshot.tag === "" ? void 0 : snapshot.tag, snapshot.commit === "" ? void 0 : snapshot.commit, snapshot.timestamp);
810
+ const useCalculated = snapshot?.useCalculatedVersion ?? config.snapshot.useCalculatedVersion;
811
+ const finalVersion = (release) => {
812
+ if (suffix === void 0 || release.type === "none") return newVersion(release);
813
+ return `${useCalculated ? newVersion(release) : "0.0.0"}-${suffix}`;
814
+ };
567
815
  const planned = [];
568
816
  for (const release of releases.values()) {
569
- const next = newVersion(release);
817
+ const next = finalVersion(release);
570
818
  if (release.oldVersion === void 0 || next === void 0) continue;
571
819
  planned.push(PlannedRelease.make({
572
820
  name: release.name,
@@ -580,8 +828,9 @@ const assembleOrHalt = (input) => {
580
828
  return ReleasePlan.make({
581
829
  releases: planned,
582
830
  changesets: relevant,
583
- ...pre === void 0 ? {} : { preState: pre }
831
+ ...pre === void 0 ? {} : { preState: pre },
832
+ snapshot: snapshot !== void 0
584
833
  });
585
834
  };
586
835
 
587
- export { PlannedRelease, ReleasePlan };
836
+ export { PlannedRelease, ReleaseContext, ReleasePlan };
package/errors.js CHANGED
@@ -47,5 +47,60 @@ var UnknownPackageError = class extends Schema.TaggedError()("UnknownPackageErro
47
47
  return `Changeset ${this.changeset} names ${this.packageName}, which is not in the workspace`;
48
48
  }
49
49
  };
50
+ /**
51
+ * A snapshot release was asked for while `.changeset/pre.json` has the
52
+ * repository in pre mode. `changeset version --snapshot` refuses the same
53
+ * way; leave pre mode (`changeset pre exit`) first.
54
+ *
55
+ * @public
56
+ */
57
+ var SnapshotPreModeError = class extends Schema.TaggedError()("SnapshotPreModeError", {
58
+ /** The pre-release tag of the pre mode the repository is in. */
59
+ preTag: Schema.String }) {
60
+ get message() {
61
+ return `A snapshot release is not allowed in pre mode (tag "${this.preTag}"); exit pre mode first`;
62
+ }
63
+ };
64
+ /**
65
+ * A snapshot prerelease template could not be filled, for one of the two
66
+ * reasons `@changesets/assemble-release-plan` refuses one:
67
+ *
68
+ * - `missingValue`: the template uses `{commit}`, `{commit-short}` or `{tag}`
69
+ * and the snapshot gave no value for it.
70
+ * - `missingPlaceholder`: the snapshot gave a tag and the template has no
71
+ * `{tag}` to put it in.
72
+ *
73
+ * @public
74
+ */
75
+ var SnapshotTemplateError = class extends Schema.TaggedError()("SnapshotTemplateError", {
76
+ /** The template that could not be filled. */
77
+ template: Schema.String,
78
+ /** The placeholder at fault. */
79
+ placeholder: Schema.Literals([
80
+ "commit",
81
+ "commit-short",
82
+ "tag"
83
+ ]),
84
+ /** Which of the two refusals this is. */
85
+ kind: Schema.Literals(["missingValue", "missingPlaceholder"])
86
+ }) {
87
+ get message() {
88
+ return this.kind === "missingValue" ? `Snapshot template "${this.template}" uses {${this.placeholder}}, which has no value` : `Snapshot template "${this.template}" has no {${this.placeholder}} placeholder, but a ${this.placeholder} was given`;
89
+ }
90
+ };
91
+ /**
92
+ * A release plan names a package the packages given to
93
+ * {@link ReleasePlan.edits} do not contain: the plan was made from a
94
+ * different workspace than the one being edited.
95
+ *
96
+ * @public
97
+ */
98
+ var MissingPackageError = class extends Schema.TaggedError()("MissingPackageError", {
99
+ /** The package the plan releases. */
100
+ packageName: Schema.String }) {
101
+ get message() {
102
+ return `The release plan releases ${this.packageName}, which is not among the packages given`;
103
+ }
104
+ };
50
105
 
51
- export { ChangesetConfigError, ChangesetParseError, UnknownPackageError };
106
+ export { ChangesetConfigError, ChangesetParseError, MissingPackageError, SnapshotPreModeError, SnapshotTemplateError, UnknownPackageError };