rolldown-pnpm-config 3.0.7 → 3.2.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/cli/exit-codes.js CHANGED
@@ -7,10 +7,17 @@
7
7
  *
8
8
  * `UpgradeUsageError` is the command's own invalid flag combination (`--format
9
9
  * json` outside `--check`/`--yes`/`--dry-run`), so it shares the parser's 64
10
- * (BSD `EX_USAGE`) rather than a resolution failure's 1.
10
+ * (BSD `EX_USAGE`) rather than a resolution failure's 1. `SyncUsageError`
11
+ * (`sync --check --local`) and `SyncConfigError` (an absent or malformed
12
+ * `sync` block) are usage errors too. Every other sync failure — membership,
13
+ * workspace discovery, the release plan, the upgrade — stays at 1.
11
14
  *
12
15
  * @internal
13
16
  */
14
- const EXIT_CODES = { UpgradeUsageError: 64 };
17
+ const EXIT_CODES = {
18
+ UpgradeUsageError: 64,
19
+ SyncUsageError: 64,
20
+ SyncConfigError: 64
21
+ };
15
22
 
16
23
  export { EXIT_CODES };
@@ -1,4 +1,7 @@
1
1
  import { Array as Array$1, Predicate } from "effect";
2
+ import { FIELD_REGISTRY } from "../registry.js";
3
+ import { sectionMerge, unionRecord } from "../runtime/strategies/arrays.js";
4
+ import { mapChildWins } from "../runtime/strategies/maps.js";
2
5
 
3
6
  // src/cli/local-merge.ts
4
7
  /** Default protocols whose existing-file override entries are preserved. @internal */
@@ -8,6 +11,53 @@ const DEFAULT_PRESERVE = [
8
11
  "workspace",
9
12
  "portal"
10
13
  ];
14
+ /**
15
+ * Fields whose runtime strategy unions the file with the managed value, derived
16
+ * from `FIELD_REGISTRY` so `export` keeps hand-added entries as install does.
17
+ * `local: { strategy: "rewrite" }` opts a field back into overwrite.
18
+ *
19
+ * @internal
20
+ */
21
+ const UNION_EXPORT_FIELDS = new Set(Object.entries(FIELD_REGISTRY).filter(([, p]) => p.strategy === "arrayUnion" || p.strategy === "arrayRecordUnion").map(([name]) => name));
22
+ /** The runtime map strategies `export` replays, the file as base and the managed value on top. */
23
+ const MAP_STRATEGIES = {
24
+ mapChildWins,
25
+ sectionMerge
26
+ };
27
+ /**
28
+ * Map fields' runtime strategy functions, keyed by field: every
29
+ * `FIELD_REGISTRY` entry whose strategy is `mapChildWins` or `sectionMerge`.
30
+ * `export` merges through the same function with the arguments the other way
31
+ * round: the file is the base and the managed value is laid on top, so a
32
+ * managed change to a key the file holds is exported (install, where the
33
+ * consumer's value wins, freezes such a key after the first export).
34
+ */
35
+ const MAP_EXPORT_STRATEGIES = new Map(Object.entries(FIELD_REGISTRY).flatMap(([name, p]) => {
36
+ const strategy = MAP_STRATEGIES[p.strategy];
37
+ return strategy === void 0 ? [] : [[name, strategy]];
38
+ }));
39
+ /**
40
+ * Map fields (`mapChildWins` and `sectionMerge` in `FIELD_REGISTRY`) whose
41
+ * file-only keys `export` keeps; on a key both hold the managed value wins.
42
+ * A deliberate consumer value goes in `local`; `local: { strategy: "rewrite" }`
43
+ * opts a field back into overwrite.
44
+ *
45
+ * @internal
46
+ */
47
+ const MAP_EXPORT_FIELDS = new Set(MAP_EXPORT_STRATEGIES.keys());
48
+ const isMap = (v) => Predicate.isObject(v) && !Array.isArray(v);
49
+ /**
50
+ * `map` without the keys `names` lists: an array of key names, or a map whose
51
+ * keys are removed. A non-map input (nothing managed, nothing in the file)
52
+ * stays absent rather than becoming an empty map.
53
+ */
54
+ function withoutKeys(map, names) {
55
+ if (!isMap(map)) return void 0;
56
+ const out = { ...map };
57
+ const keys = Array.isArray(names) ? names.map(String) : isMap(names) ? Object.keys(names) : [];
58
+ for (const k of keys) delete out[k];
59
+ return out;
60
+ }
11
61
  const DIRECTIVE_KEYS = /* @__PURE__ */ new Set([
12
62
  "preserve",
13
63
  "value",
@@ -42,6 +92,11 @@ function combine(managed, value, strategy) {
42
92
  for (const k of Object.keys(v)) delete out[k];
43
93
  return out;
44
94
  }
95
+ /** Union the file's value into `value`; records of string arrays union per key, as the runtime does. */
96
+ function unionFile(value, parsed) {
97
+ if (isMap(parsed) && (value === void 0 || isMap(value))) return unionRecord(value ?? {}, parsed);
98
+ return combine(value, parsed, "union");
99
+ }
45
100
  /**
46
101
  * Compute the effective value of one field from the managed value, the
47
102
  * `config.local[field]` directive (or bare value / undefined), and the parsed
@@ -57,6 +112,16 @@ function applyLocalDirective(managed, raw, parsed, field) {
57
112
  if (strat && strat !== "rewrite" && directive.value !== void 0) result = combine(managed, directive.value, strat);
58
113
  else if (directive.value !== void 0 && directive.strategy !== "rewrite") result = directive.value;
59
114
  else result = managed;
115
+ if (UNION_EXPORT_FIELDS.has(field) && directive.strategy !== "rewrite" && parsed !== void 0) {
116
+ if (directive.strategy === "difference" && directive.value !== void 0) result = combine(unionFile(managed, parsed), directive.value, "difference");
117
+ else result = unionFile(result, parsed);
118
+ }
119
+ const mapStrategy = MAP_EXPORT_STRATEGIES.get(field);
120
+ if (mapStrategy !== void 0 && directive.strategy !== "rewrite") {
121
+ const mergeFile = (value) => isMap(parsed) && (value === void 0 || isMap(value)) ? mapStrategy(parsed, value, { rootName: void 0 }).merged : value;
122
+ if (directive.strategy === "difference" && directive.value !== void 0) result = withoutKeys(mergeFile(managed), directive.value);
123
+ else result = mergeFile(result);
124
+ }
60
125
  if (field === "overrides") {
61
126
  const protocols = directive.preserve ?? DEFAULT_PRESERVE;
62
127
  const base = Predicate.isObject(result) ? { ...result } : {};
@@ -69,4 +134,4 @@ function applyLocalDirective(managed, raw, parsed, field) {
69
134
  return result;
70
135
  }
71
136
 
72
- export { DEFAULT_PRESERVE, applyLocalDirective, isLocalDirective };
137
+ export { DEFAULT_PRESERVE, MAP_EXPORT_FIELDS, UNION_EXPORT_FIELDS, applyLocalDirective, isLocalDirective };
package/cli/main.js CHANGED
@@ -16,8 +16,9 @@ import { CLI_VERSION } from "./version.js";
16
16
  * kit reads it from when `env.stderrIsTerminal` is omitted.
17
17
  *
18
18
  * The registry resolver is provided here, at the edge, so a test drives the
19
- * same command tree against a stub resolver. It spawns `pnpm view` through the
20
- * platform's `ChildProcessSpawner`, reads pnpm's settings from
19
+ * same command tree against a stub resolver. It reads the registry through
20
+ * `@effected/npm`'s `NpmRegistry` (npmrc routing, auth, proxy and CA settings
21
+ * as pnpm applies them), reads pnpm's settings from
21
22
  * `process.cwd()` / `process.env` / `process.platform`, and takes `FileSystem`
22
23
  * and `Path` from `NodeServices.layer`, provided by `main`.
23
24
  *
@@ -17,7 +17,7 @@ import { overlayWorkspace } from "./workspace-overlay.js";
17
17
  */
18
18
  function buildPreviewViews(input) {
19
19
  const meta = {
20
- localKeys: new Set(input.local ? Object.keys(input.local) : []),
20
+ localKeys: new Set(Object.keys(input.local ?? {}).filter((k) => WORKSPACE_FIELDS.has(k))),
21
21
  managedKeys: WORKSPACE_FIELDS
22
22
  };
23
23
  const effective = effectiveManaged(input.managed, input.local, input.parsed, input.manifest, input.rootName);
package/cli/root.js CHANGED
@@ -2,6 +2,7 @@ import { CliAudience } from "@effected/cli-kit";
2
2
  import { Command } from "effect/cli";
3
3
  import { exportCommand } from "./commands/export.js";
4
4
  import { previewCommand } from "./commands/preview.js";
5
+ import { syncCommand } from "./commands/sync.js";
5
6
  import { upgradeCommand } from "./commands/upgrade.js";
6
7
 
7
8
  // src/cli/root.ts
@@ -15,7 +16,8 @@ import { upgradeCommand } from "./commands/upgrade.js";
15
16
  const rootCommand = Command.make("rolldown-pnpm-config").pipe(Command.withSharedFlags(CliAudience.flags()), Command.withSubcommands([
16
17
  upgradeCommand,
17
18
  exportCommand,
18
- previewCommand
19
+ previewCommand,
20
+ syncCommand
19
21
  ]));
20
22
 
21
23
  export { rootCommand };
@@ -0,0 +1,22 @@
1
+ import { byCatalog } from "./running-list.js";
2
+
3
+ // src/cli/sync/commit-message.ts
4
+ /**
5
+ * The commit message for a set of moves: a conventional-commit headline, a
6
+ * blank line, then one bullet per package.
7
+ *
8
+ * @remarks
9
+ * With no moves the message is the headline alone. Package names are written
10
+ * bare, never as inline code: commitlint presets such as
11
+ * `@savvy-web/commitlint`'s `silk/body-no-markdown` reject a body with more
12
+ * than a couple of code spans, and a sync can move dozens of packages.
13
+ *
14
+ * @internal
15
+ */
16
+ function renderCommitMessage(scope, moves) {
17
+ const headline = `chore(${scope}): sync catalog to the next release versions`;
18
+ if (moves.length === 0) return `${headline}\n`;
19
+ return `${headline}\n\n${byCatalog(moves).flatMap(([, group]) => group.map((move) => `- ${move.pkg} ${move.from} -> ${move.to}`)).join("\n")}\n`;
20
+ }
21
+
22
+ export { renderCommitMessage };
@@ -0,0 +1,83 @@
1
+ import { CliDoc } from "@effected/cli-kit";
2
+ import { Data, Effect, Schema } from "effect";
3
+ import { failureDoc } from "../render/report.js";
4
+
5
+ // src/cli/sync/config.ts
6
+ /**
7
+ * Typed failure raised when the `sync` block is absent or malformed. A usage
8
+ * error: the CLI maps it to exit 64.
9
+ *
10
+ * @internal
11
+ */
12
+ var SyncConfigError = class extends Data.TaggedError("SyncConfigError") {
13
+ /** The failure report `CliRuntime.main` prints: the message, without the class name. */
14
+ [CliDoc]() {
15
+ return failureDoc(this.message);
16
+ }
17
+ };
18
+ const Names = Schema.Array(Schema.String);
19
+ const SyncSchema = Schema.Struct({
20
+ catalog: Schema.String,
21
+ members: Schema.Struct({
22
+ scope: Schema.NonEmptyString,
23
+ packages: Schema.optionalKey(Names),
24
+ exclude: Schema.optionalKey(Names)
25
+ }),
26
+ changeset: Schema.optionalKey(Schema.Struct({
27
+ path: Schema.optionalKey(Schema.String),
28
+ bump: Schema.optionalKey(Schema.Literals(["patch", "minor"]))
29
+ })),
30
+ commit: Schema.optionalKey(Schema.Struct({
31
+ scope: Schema.optionalKey(Schema.String),
32
+ messagePath: Schema.optionalKey(Schema.String)
33
+ })),
34
+ floors: Schema.optionalKey(Schema.Boolean),
35
+ local: Schema.optionalKey(Schema.Struct({
36
+ pnpmfile: Schema.optionalKey(Schema.String),
37
+ catalogs: Schema.optionalKey(Names)
38
+ }))
39
+ });
40
+ const decodeSync = Schema.decodeUnknownEffect(SyncSchema);
41
+ /**
42
+ * Decode the statically evaluated `sync` block of a plugin config and apply
43
+ * its defaults. Unknown keys are rejected so a typo cannot pass for an absent
44
+ * setting.
45
+ *
46
+ * @internal
47
+ */
48
+ function resolveSyncConfig(config) {
49
+ if (config.sync === void 0) return Effect.fail(new SyncConfigError({ message: "no `sync` block: add `sync: { catalog, members: { scope } }` to the PnpmConfigPlugin config" }));
50
+ return decodeSync(config.sync, {
51
+ onExcessProperty: "error",
52
+ errors: "all"
53
+ }).pipe(Effect.mapError((error) => new SyncConfigError({ message: `invalid \`sync\` block: ${error.message}` })), Effect.map((sync) => ({
54
+ catalog: sync.catalog,
55
+ scope: sync.members.scope,
56
+ packages: sync.members.packages,
57
+ exclude: sync.members.exclude ?? [],
58
+ changesetPath: sync.changeset?.path ?? ".changeset/catalog-sync.md",
59
+ bump: sync.changeset?.bump ?? "patch",
60
+ commitScope: sync.commit?.scope ?? sync.catalog,
61
+ messagePath: sync.commit?.messagePath ?? ".changeset/catalog-sync.commit.txt",
62
+ floors: sync.floors ?? false,
63
+ pnpmfile: sync.local?.pnpmfile ?? "dist/prod/npm/pkg/pnpmfile.mjs",
64
+ localCatalogs: sync.local?.catalogs
65
+ })));
66
+ }
67
+ /**
68
+ * Decode the `sync` block from what `evaluatePluginConfig` read out of
69
+ * `configFile`, naming the real problem when there is no config to read: a
70
+ * file that does not parse, or one with no `PnpmConfigPlugin(...)` call, is not
71
+ * a config with a missing `sync` block. Each is a usage error (exit 64).
72
+ *
73
+ * @internal
74
+ */
75
+ function resolveEvaluatedSync(evaluated, configFile) {
76
+ if (evaluated.config === null) {
77
+ const message = evaluated.errors.length > 0 ? `cannot parse ${configFile}:\n${evaluated.errors.map((e) => ` ${e}`).join("\n")}` : `no PnpmConfigPlugin(...) call found in ${configFile}: sync reads its \`sync\` block from that call's config`;
78
+ return Effect.fail(new SyncConfigError({ message }));
79
+ }
80
+ return resolveSyncConfig(evaluated.config);
81
+ }
82
+
83
+ export { SyncConfigError, resolveEvaluatedSync, resolveSyncConfig };
@@ -0,0 +1,146 @@
1
+ import { ChangesetConfig, PendingChangeset, PendingChangesets, PreState, ReleasePlan } from "@effected/changesets";
2
+ import { WorkspaceDiscovery } from "@effected/workspaces";
3
+ import { Effect, FileSystem, Option, Path } from "effect";
4
+ import { ReleasePlanError, discoveryLayer } from "./release-plan.js";
5
+
6
+ // src/cli/sync/floors.ts
7
+ /**
8
+ * Every file the floor pass owns starts with this, under `.changeset/`.
9
+ *
10
+ * @internal
11
+ */
12
+ const FLOOR_PREFIX = "breaking-floor-";
13
+ const floorFile = (name) => `${FLOOR_PREFIX}${name.replace(/^@/, "").replace(/\//g, "-")}.md`;
14
+ const isFloorFile = (file) => file.startsWith("breaking-floor-") && file.endsWith(".md");
15
+ /** The changeset raising one package, with a line per dependency whose floor it crosses. */
16
+ const renderFloorChangeset = (raised) => {
17
+ const lines = raised.causes.map((cause) => `- Requires \`${cause.dependency}\` ${cause.newVersion} (\`${cause.kind}\`: \`${cause.range}\`), a breaking release from ${cause.oldVersion}. A consumer still on ${cause.oldVersion} cannot install this version beside it, so this release leaves its own version line too.`);
18
+ const upgrade = raised.causes.map((cause) => `\`${cause.dependency}\` to ${cause.newVersion}`).join(", ");
19
+ return `---\n"${raised.name}": ${raised.required}\n---\n\n## Breaking Changes\n\n${lines.join("\n")}\n\nTo upgrade, move ${upgrade} in the same install as this release.\n`;
20
+ };
21
+ /**
22
+ * Raise every release whose published floor crosses a dependency's breaking
23
+ * line, then plan again until none does.
24
+ *
25
+ * @remarks
26
+ * `@changesets/assemble-release-plan` bumps a dependent `patch` however far its
27
+ * dependency moves. Under `workspace:^` a dependent released beside a breaking
28
+ * 0.x minor publishes a floor on the new minor, so a consumer holding the old
29
+ * line of both resolves the patch and gets a dependency it cannot satisfy.
30
+ * `ReleasePlan.breakingFloors` finds those releases. A raised package can cross
31
+ * its own dependents' floors, so each pass feeds the raises back in as synthetic
32
+ * changesets; the package count bounds the passes.
33
+ *
34
+ * Our own files are read out of the base before any plan is made: an obsolete
35
+ * one naming a removed package would fail the plan instead of being deleted, and
36
+ * a raise must never be its own evidence.
37
+ */
38
+ const planFloors = Effect.fn("Sync.planFloors")(function* (rootDir) {
39
+ const discovered = yield* (yield* WorkspaceDiscovery).listPackagesIn(rootDir);
40
+ const config = yield* ChangesetConfig.read(rootDir);
41
+ const pending = yield* PendingChangesets.read(rootDir);
42
+ const pre = yield* PreState.read(rootDir);
43
+ const base = pending.filter((changeset) => !isFloorFile(changeset.file));
44
+ const members = discovered.filter((pkg) => !pkg.isRootWorkspace);
45
+ const packages = members.length > 0 ? members : discovered;
46
+ const raised = /* @__PURE__ */ new Map();
47
+ for (let pass = 0; pass <= packages.length; pass++) {
48
+ const synthetic = [...raised.values()].map((r) => PendingChangeset.make({
49
+ file: floorFile(r.name),
50
+ releases: /* @__PURE__ */ new Map([[r.name, r.required]]),
51
+ summary: ""
52
+ }));
53
+ const plan = yield* Effect.fromResult(ReleasePlan.assemble({
54
+ packages,
55
+ changesets: [...base, ...synthetic],
56
+ config,
57
+ ...Option.isSome(pre) ? { pre: pre.value } : {}
58
+ }));
59
+ const floors = yield* Effect.fromResult(ReleasePlan.breakingFloors(plan, {
60
+ packages: discovered,
61
+ config
62
+ }));
63
+ if (floors.length === 0) return [...raised.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
64
+ for (const floor of floors) raised.set(floor.name, {
65
+ name: floor.name,
66
+ required: floor.required,
67
+ causes: floor.causes
68
+ });
69
+ }
70
+ return yield* Effect.die(/* @__PURE__ */ new Error("breaking floors did not settle; a raise should never undo another"));
71
+ });
72
+ /**
73
+ * Plan the breaking-floor changesets for the workspace at `rootDir`: the raised
74
+ * releases, and the edits that make `.changeset/` hold exactly those and none
75
+ * other of ours. Writes nothing.
76
+ *
77
+ * @remarks
78
+ * The files are derived. Every run recomputes them from the other changesets,
79
+ * rewrites those still needed and deletes the rest, so a floor that stops
80
+ * crossing takes its file with it. A plan that cannot be read fails
81
+ * {@link ReleasePlanError} rather than reporting "nothing crosses".
82
+ *
83
+ * @internal
84
+ */
85
+ const planFloorEdits = Effect.fn("Sync.planFloorEdits")(function* (rootDir) {
86
+ const fs = yield* FileSystem.FileSystem;
87
+ const path = yield* Path.Path;
88
+ const raised = yield* planFloors(rootDir).pipe(Effect.provide(discoveryLayer(rootDir)), Effect.mapError((error) => new ReleasePlanError({ message: `Release plan could not be read: ${error.message}` })));
89
+ const dir = path.join(rootDir, ".changeset");
90
+ const edits = [];
91
+ const wanted = /* @__PURE__ */ new Set();
92
+ for (const r of raised) {
93
+ const file = floorFile(r.name);
94
+ wanted.add(file);
95
+ const content = renderFloorChangeset(r);
96
+ const target = path.join(dir, file);
97
+ const current = yield* fs.readFileString(target).pipe(Effect.option);
98
+ if (Option.isNone(current) || current.value !== content) edits.push({
99
+ path: `.changeset/${file}`,
100
+ content
101
+ });
102
+ }
103
+ const present = (yield* fs.readDirectory(dir).pipe(Effect.catchTag("PlatformError", (error) => error.reason._tag === "NotFound" ? Effect.succeed([]) : Effect.fail(error)), Effect.mapError((error) => new ReleasePlanError({ message: `Release plan could not be read: ${error.message}` })))).filter(isFloorFile).sort();
104
+ for (const file of present) if (!wanted.has(file)) edits.push({
105
+ path: `.changeset/${file}`,
106
+ content: null
107
+ });
108
+ return {
109
+ raised,
110
+ edits
111
+ };
112
+ });
113
+ /**
114
+ * Apply `edits` under `rootDir`. Parent directories are created; deleting a
115
+ * file that is already gone is not an error.
116
+ *
117
+ * @internal
118
+ */
119
+ const applyFloorEdits = Effect.fn("Sync.applyFloorEdits")(function* (rootDir, edits) {
120
+ const fs = yield* FileSystem.FileSystem;
121
+ const path = yield* Path.Path;
122
+ for (const { path: relative, content } of edits) {
123
+ const target = path.join(rootDir, relative);
124
+ if (content === null) yield* fs.remove(target, { force: true });
125
+ else {
126
+ yield* fs.makeDirectory(path.dirname(target), { recursive: true });
127
+ yield* fs.writeFileString(target, content);
128
+ }
129
+ }
130
+ });
131
+ /**
132
+ * One line per edit, for a person reading a log or a red check.
133
+ *
134
+ * @internal
135
+ */
136
+ function describeFloorEdits(raised, edits) {
137
+ const byPath = new Map(raised.map((r) => [`.changeset/${floorFile(r.name)}`, r]));
138
+ return edits.map(({ path, content }) => {
139
+ const r = byPath.get(path);
140
+ if (content === null || r === void 0) return ` ${path} (no longer needed)\n`;
141
+ const deps = r.causes.map((c) => `${c.dependency} ${c.oldVersion} -> ${c.newVersion}`).join(", ");
142
+ return ` ${r.name} -> ${r.required} (crosses ${deps})\n`;
143
+ }).join("");
144
+ }
145
+
146
+ export { FLOOR_PREFIX, applyFloorEdits, describeFloorEdits, planFloorEdits };
@@ -0,0 +1,69 @@
1
+ import { existsSync } from "node:fs";
2
+ import { pathToFileURL } from "node:url";
3
+ import { Fmt } from "@effected/cli-kit";
4
+ import { Data, Effect, Predicate } from "effect";
5
+
6
+ // src/cli/sync/local-gate.ts
7
+ /**
8
+ * Typed failure of the offline local gate (the built pnpmfile is missing or
9
+ * cannot be evaluated).
10
+ *
11
+ * @internal
12
+ */
13
+ var LocalGateError = class extends Data.TaggedError("LocalGateError") {};
14
+ /**
15
+ * Import the built pnpmfile and ask its `updateConfig` hook what an empty
16
+ * consumer config receives. Offline; writes nothing.
17
+ *
18
+ * @internal
19
+ */
20
+ function readServedCatalogs(pnpmfilePath) {
21
+ if (!existsSync(pnpmfilePath)) return Effect.fail(new LocalGateError({ message: `no built pnpmfile at ${pnpmfilePath}; build the plugin first` }));
22
+ return Effect.tryPromise({
23
+ try: async () => {
24
+ return (await (await import(pathToFileURL(pnpmfilePath).href)).hooks.updateConfig({})).catalogs ?? {};
25
+ },
26
+ catch: (cause) => new LocalGateError({ message: `cannot evaluate ${pnpmfilePath}: ${Fmt.errorText(cause)}` })
27
+ });
28
+ }
29
+ /**
30
+ * The catalogs the export writes into this repo's own workspace file: an
31
+ * explicit `local.catalogs` wins, otherwise every served catalog except the
32
+ * sync catalog and its derived `:peers` and `:exact` siblings, which lag it
33
+ * between releases in exactly the same way.
34
+ *
35
+ * @internal
36
+ */
37
+ function exportedCatalogNames(served, sync) {
38
+ if (sync.localCatalogs !== void 0) return sync.localCatalogs;
39
+ const managed = /* @__PURE__ */ new Set([
40
+ sync.catalog,
41
+ `${sync.catalog}:peers`,
42
+ `${sync.catalog}:exact`
43
+ ]);
44
+ return Object.keys(served).filter((name) => !managed.has(name));
45
+ }
46
+ /**
47
+ * Per exported catalog, the packages whose served range differs from the
48
+ * parsed `pnpm-workspace.yaml` mapping (its `catalogs` key holds the named
49
+ * catalogs). Rows are human-readable; empty means in sync.
50
+ *
51
+ * @internal
52
+ */
53
+ function exportDrift(served, names, workspace) {
54
+ const catalogs = Predicate.isObject(workspace.catalogs) ? workspace.catalogs : {};
55
+ const rows = [];
56
+ for (const name of names) {
57
+ const want = served[name] ?? {};
58
+ const raw = catalogs[name];
59
+ if (!Predicate.isObject(raw)) {
60
+ rows.push(` ${name}: absent from pnpm-workspace.yaml`);
61
+ continue;
62
+ }
63
+ const have = raw;
64
+ for (const pkg of [.../* @__PURE__ */ new Set([...Object.keys(want), ...Object.keys(have)])].sort()) if (want[pkg] !== have[pkg]) rows.push(` ${name}.${pkg} served ${want[pkg] ?? "(absent)"}, pnpm-workspace.yaml ${have[pkg] ?? "(absent)"}`);
65
+ }
66
+ return rows;
67
+ }
68
+
69
+ export { LocalGateError, exportDrift, exportedCatalogNames, readServedCatalogs };
@@ -0,0 +1,118 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CliDoc } from "@effected/cli-kit";
4
+ import { GlobPattern } from "@effected/glob";
5
+ import { Walker } from "@effected/walker";
6
+ import { getWorkspacePackagesSync } from "@effected/workspaces";
7
+ import { nodeSyncOps } from "@effected/workspaces/node-sync";
8
+ import { Data, Effect, FileSystem, Option, Path, Result, Schema } from "effect";
9
+ import { readCatalogSource } from "../commands/upgrade.js";
10
+ import { failureDoc } from "../render/report.js";
11
+
12
+ // src/cli/sync/membership.ts
13
+ /**
14
+ * Typed failure raised when the workspace cannot be discovered, or discovery
15
+ * leaves nothing to check against. A finding, not a usage error: exit 1.
16
+ *
17
+ * @internal
18
+ */
19
+ var SyncWorkspaceError = class extends Data.TaggedError("SyncWorkspaceError") {
20
+ /** The failure report `CliRuntime.main` prints: the message, without the class name. */
21
+ [CliDoc]() {
22
+ return failureDoc(this.message);
23
+ }
24
+ };
25
+ const PackageName = Schema.fromJsonString(Schema.Struct({ name: Schema.String }));
26
+ const decodePackageName = Schema.decodeUnknownEffect(PackageName);
27
+ /**
28
+ * The nearest `package.json` at or above the config file: the plugin
29
+ * package's manifest.
30
+ *
31
+ * @internal
32
+ */
33
+ const pluginManifest = Effect.fn("Sync.pluginManifest")(function* (configFile) {
34
+ const path = yield* Path.Path;
35
+ const dirs = yield* Walker.ascend(path.dirname(path.resolve(configFile)));
36
+ const found = yield* Walker.findUpward(dirs, (dir) => [path.join(dir, "package.json")]);
37
+ if (Option.isNone(found)) return yield* new SyncWorkspaceError({ message: `no package.json found at or above ${configFile}` });
38
+ return found.value;
39
+ });
40
+ /**
41
+ * The name of the plugin package: the `name` of the nearest `package.json` at
42
+ * or above the config file. Membership always excludes it.
43
+ *
44
+ * @internal
45
+ */
46
+ const pluginPackageName = Effect.fn("Sync.pluginPackageName")(function* (configFile) {
47
+ const fs = yield* FileSystem.FileSystem;
48
+ const manifest = yield* pluginManifest(configFile);
49
+ return yield* fs.readFileString(manifest).pipe(Effect.flatMap(decodePackageName), Effect.map((m) => m.name), Effect.mapError(() => new SyncWorkspaceError({ message: `cannot read a package name from ${manifest}` })));
50
+ });
51
+ function compile(source) {
52
+ return Result.mapError(GlobPattern.compileResult(source), (error) => new SyncWorkspaceError({ message: `invalid glob "${source}": ${error.message}` }));
53
+ }
54
+ /**
55
+ * Publishable workspace packages in `sync.scope`, sorted: `publishConfig.access`
56
+ * is `"public"`, the name is not excluded and is not the plugin itself. A scope
57
+ * that matches no workspace package name at all, whatever its access, fails.
58
+ * `sync.packages`, when set, limits discovery to members whose workspace-relative
59
+ * path matches one of its globs. Unlike the upgrade resolver, an unreadable
60
+ * workspace fails rather than reading as empty: an empty list would pass the
61
+ * gate for the wrong reason.
62
+ *
63
+ * @internal
64
+ */
65
+ function publishableMembers(rootDir, sync, pluginName) {
66
+ return Effect.gen(function* () {
67
+ if (!existsSync(join(rootDir, "pnpm-workspace.yaml"))) return yield* new SyncWorkspaceError({ message: `no pnpm-workspace.yaml found in ${rootDir}` });
68
+ const scope = yield* Effect.fromResult(compile(sync.scope));
69
+ const excludes = yield* Effect.fromResult(Result.all(sync.exclude.map(compile)));
70
+ const paths = yield* Effect.fromResult(Result.all((sync.packages ?? []).map(compile)));
71
+ const packages = yield* Effect.try({
72
+ try: () => getWorkspacePackagesSync(rootDir, nodeSyncOps),
73
+ catch: (error) => new SyncWorkspaceError({ message: `cannot discover workspace packages in ${rootDir}: ${error instanceof Error ? error.message : String(error)}` })
74
+ });
75
+ if (!packages.some((pkg) => scope.matches(pkg.name))) return yield* new SyncWorkspaceError({ message: `members.scope "${sync.scope}" matches no workspace package in ${rootDir}: check it for a typo` });
76
+ return packages.filter((pkg) => pkg.publishConfig?.access === "public" && pkg.name !== pluginName && scope.matches(pkg.name) && !excludes.some((glob) => glob.matches(pkg.name)) && (sync.packages === void 0 || paths.some((glob) => glob.matches(pkg.relativePath)))).map((pkg) => pkg.name).sort();
77
+ });
78
+ }
79
+ /**
80
+ * Compare the workspace's publishable members with the packages the sync
81
+ * catalog names in the config at `configFile`.
82
+ *
83
+ * @internal
84
+ */
85
+ const checkMembership = Effect.fn("Sync.checkMembership")(function* (configFile, rootDir, sync) {
86
+ const publishable = yield* publishableMembers(rootDir, sync, yield* pluginPackageName(configFile));
87
+ const { entries } = yield* readCatalogSource(configFile, sync.catalog);
88
+ const catalogued = entries.map((entry) => entry.pkg);
89
+ const scope = yield* Effect.fromResult(compile(sync.scope));
90
+ const inScope = catalogued.filter((name) => scope.matches(name));
91
+ if (publishable.length === 0 && inScope.length > 0) return yield* new SyncWorkspaceError({ message: `no publishable package matches ${sync.scope}, yet the \`${sync.catalog}\` catalog names ${inScope.length}: a member that is \`private\` without \`publishConfig.access: "public"\` is not publishable` });
92
+ const named = new Set(catalogued);
93
+ return {
94
+ missing: publishable.filter((name) => !named.has(name)),
95
+ publishable,
96
+ catalogued
97
+ };
98
+ });
99
+ /**
100
+ * What to do about a membership gap: the last line of {@link membershipMessage}.
101
+ *
102
+ * @internal
103
+ */
104
+ const MEMBERSHIP_REMEDY = "Add an entry for each at the PnpmConfigPlugin(...) call site with `source: \"workspace\"`.";
105
+ /**
106
+ * The failure text for publishable packages the catalog does not name.
107
+ *
108
+ * @internal
109
+ */
110
+ function membershipMessage(missing, configFile) {
111
+ return [
112
+ `Publishable packages missing from the catalog in ${configFile}:`,
113
+ ...missing.map((name) => ` - ${name}`),
114
+ MEMBERSHIP_REMEDY
115
+ ].join("\n");
116
+ }
117
+
118
+ export { MEMBERSHIP_REMEDY, SyncWorkspaceError, checkMembership, membershipMessage, pluginManifest, pluginPackageName, publishableMembers };
@@ -0,0 +1,49 @@
1
+ import { ReleasePlan } from "@effected/changesets";
2
+ import { CliDoc } from "@effected/cli-kit";
3
+ import { WorkspaceDiscovery, WorkspaceRoot } from "@effected/workspaces";
4
+ import { Data, Effect, Layer } from "effect";
5
+ import { failureDoc } from "../render/report.js";
6
+
7
+ // src/cli/sync/release-plan.ts
8
+ /**
9
+ * Typed failure raised when the release plan cannot be read. A finding, not an
10
+ * empty plan: an empty plan would pass the ripple gate with nothing checked.
11
+ *
12
+ * @internal
13
+ */
14
+ var ReleasePlanError = class extends Data.TaggedError("ReleasePlanError") {
15
+ /** The failure report `CliRuntime.main` prints: the message, without the class name. */
16
+ [CliDoc]() {
17
+ return failureDoc(this.message);
18
+ }
19
+ };
20
+ /**
21
+ * Workspace discovery rooted at `rootDir`, for the release-plan reads. Needs
22
+ * `FileSystem` and `Path` from the caller; it exposes only `WorkspaceDiscovery`.
23
+ *
24
+ * @internal
25
+ */
26
+ const discoveryLayer = (rootDir) => WorkspaceDiscovery.layer({ cwd: rootDir }).pipe(Layer.provide(WorkspaceRoot.layer));
27
+ /**
28
+ * Every package changesets would release from `rootDir`, and the version it
29
+ * would get, ripples included.
30
+ *
31
+ * @remarks
32
+ * `@effected/changesets` computes the true plan (and holds it to
33
+ * `@changesets/get-release-plan` in its own tests), so this asks it rather than
34
+ * reimplementing changesets' dependency resolution. A package bumped only as a
35
+ * dependency ripple has no changeset naming it, so the catalog goes stale on
36
+ * exactly the branch where it matters. `type: "none"` entries are listed by
37
+ * changesets but not released; taking their version would pin the catalog to a
38
+ * version nothing publishes.
39
+ *
40
+ * @internal
41
+ */
42
+ const readReleasePlan = Effect.fn("Sync.readReleasePlan")(function* (rootDir) {
43
+ const plan = yield* ReleasePlan.read(rootDir).pipe(Effect.provide(discoveryLayer(rootDir)), Effect.mapError((error) => new ReleasePlanError({ message: `Release plan could not be read: ${error.message}` })));
44
+ const versions = /* @__PURE__ */ new Map();
45
+ for (const release of plan.releases) if (release.type !== "none") versions.set(release.name, release.newVersion);
46
+ return versions;
47
+ });
48
+
49
+ export { ReleasePlanError, discoveryLayer, readReleasePlan };