rolldown-pnpm-config 2.5.2 → 3.0.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/README.md CHANGED
@@ -35,7 +35,6 @@ export const plugin = {
35
35
  allowBuilds: { esbuild: true },
36
36
  strictDepBuilds: true,
37
37
  minimumReleaseAge: { value: 1440, enforcement: "warn" },
38
- confirmModulesPurge: false,
39
38
  } satisfies PluginConfig;
40
39
  ```
41
40
 
@@ -1,7 +1,7 @@
1
- import { DESCRIPTORS } from "../../descriptors/index.js";
2
1
  import { discoverOwnedPatches, withResolvedBuildPatches } from "../../patches/build.js";
3
2
  import { reconcilePatches } from "../../patches/reconcile.js";
4
3
  import { freeze } from "../../plugin/freeze.js";
4
+ import { WORKSPACE_FIELDS } from "../../registry.js";
5
5
  import { resolveRootName } from "../../runtime/ctx.js";
6
6
  import { WorkingDirectory, resolveWorkspacePath } from "../cwd.js";
7
7
  import { buildDiff } from "../diff/build.js";
@@ -12,11 +12,11 @@ import { legend } from "../render/legend.js";
12
12
  import { printView } from "../render/print.js";
13
13
  import { failureDoc } from "../render/report.js";
14
14
  import { findConfigFiles, pickConfigCandidate } from "../select-file.js";
15
- import { canonicalize, writeWorkspace } from "../workspace-file.js";
16
15
  import { overlayWorkspace } from "../workspace-overlay.js";
17
16
  import { Data, Effect, Option, Predicate } from "effect";
18
17
  import { dirname, relative } from "node:path";
19
18
  import { CliDoc, CliMessage } from "@effected/cli-kit";
19
+ import { PnpmWorkspaceFile } from "@effected/pnpm";
20
20
  import { existsSync } from "node:fs";
21
21
  import { Argument, Command, Flag } from "effect/cli";
22
22
  import { AtomicFile } from "@effected/files";
@@ -34,13 +34,6 @@ var ExportError = class extends Data.TaggedError("ExportError") {
34
34
  }
35
35
  };
36
36
  /**
37
- * The set of pnpm config keys that belong in pnpm-workspace.yaml
38
- * (i.e. descriptors with `workspaceYaml: true`).
39
- *
40
- * @internal
41
- */
42
- const WORKSPACE_FIELDS = new Set(Object.entries(DESCRIPTORS).filter(([, d]) => d.workspaceYaml).map(([k]) => k));
43
- /**
44
37
  * Export core: freeze the plugin config first, then apply excludeByRepo and
45
38
  * local directives via the effective pipeline, overlay onto the existing
46
39
  * pnpm-workspace.yaml (or create fresh), and write the result. In preview
@@ -50,7 +43,7 @@ const WORKSPACE_FIELDS = new Set(Object.entries(DESCRIPTORS).filter(([, d]) => d
50
43
  */
51
44
  function runExport(opts) {
52
45
  return Effect.gen(function* () {
53
- const { config, localCfg, path, parsed, source } = yield* loadConfigAndWorkspace(opts, (message) => new ExportError({ message }));
46
+ const { config, localCfg, path, parsed, file } = yield* loadConfigAndWorkspace(opts, (message) => new ExportError({ message }));
54
47
  const pluginConfig = config;
55
48
  const owned = discoverOwnedPatches(pluginConfig, dirname(opts.configFile));
56
49
  const resolvedConfig = withResolvedBuildPatches(pluginConfig, dirname(opts.configFile), owned);
@@ -77,9 +70,9 @@ function runExport(opts) {
77
70
  exists: existsSync
78
71
  });
79
72
  const merged = overlayWorkspace(effective, parsed);
80
- const rendered = writeWorkspace(source, merged);
73
+ const rendered = yield* Effect.fromResult(file.writeResult(merged)).pipe(Effect.mapError((e) => new ExportError({ message: e.message })));
81
74
  const localKeys = new Set(Object.keys(localCfg ?? {}));
82
- const tree = buildDiff(canonicalize(parsed), canonicalize(merged), {
75
+ const tree = buildDiff(PnpmWorkspaceFile.canonicalize(parsed), PnpmWorkspaceFile.canonicalize(merged), {
83
76
  localKeys,
84
77
  managedKeys: WORKSPACE_FIELDS
85
78
  });
@@ -135,4 +128,4 @@ const exportCommand = Command.make("export", {
135
128
  for (const k of result.report.keyMismatches) yield* CliMessage.warning(`patch entry "${k}" does not match its filename`);
136
129
  })).pipe(Command.withDescription("Materialize the plugin config into pnpm-workspace.yaml (--dry-run to preview)"));
137
130
 
138
- export { ExportError, WORKSPACE_FIELDS, exportCommand, runExport };
131
+ export { ExportError, exportCommand, runExport };
@@ -1,4 +1,5 @@
1
1
  import { freeze } from "../../plugin/freeze.js";
2
+ import { WORKSPACE_FIELDS } from "../../registry.js";
2
3
  import { resolveRootName } from "../../runtime/ctx.js";
3
4
  import { WorkingDirectory, resolveWorkspacePath } from "../cwd.js";
4
5
  import { loadConfigAndWorkspace } from "../load-config.js";
@@ -8,7 +9,6 @@ import { printView } from "../render/print.js";
8
9
  import { failureDoc } from "../render/report.js";
9
10
  import { findConfigFiles, pickConfigCandidate } from "../select-file.js";
10
11
  import { previewScreen } from "../ui/screens.js";
11
- import { WORKSPACE_FIELDS } from "./export.js";
12
12
  import { Data, Effect, Option } from "effect";
13
13
  import { dirname } from "node:path";
14
14
  import { CliDoc, CliInteractive } from "@effected/cli-kit";
@@ -9,7 +9,7 @@ import { derivePeerRange } from "../peer-range.js";
9
9
  import { defaultPick, planEntry } from "../plan.js";
10
10
  import { readConfigReleaseAge } from "../release-age.js";
11
11
  import { failureDoc, warningDoc } from "../render/report.js";
12
- import { RegistryResolver } from "../resolve.js";
12
+ import { RegistryResolver, ResolveError } from "../resolve.js";
13
13
  import { applyEdits } from "../rewrite.js";
14
14
  import { filterEntriesByCatalog, findConfigFiles, pickConfigCandidate } from "../select-file.js";
15
15
  import { summaryDoc } from "../summary.js";
@@ -21,10 +21,10 @@ import { findWorkspaceRoot, makeWorkspaceResolver } from "../workspace-resolve.j
21
21
  import { Clock, Data, Effect, FileSystem, Option, Result } from "effect";
22
22
  import { dirname } from "node:path";
23
23
  import { CliDoc, CliExit, CliFormat, CliInteractive, CliMessage, Doc, Fmt } from "@effected/cli-kit";
24
+ import { ReleaseAgeGate } from "@effected/pnpm";
24
25
  import { Argument, Command, Flag } from "effect/cli";
25
26
  import { AtomicFile } from "@effected/files";
26
27
  import { CliUi } from "@effected/cli-kit/ui";
27
- import { ReleaseAgeGate } from "@effected/npm";
28
28
 
29
29
  // src/cli/commands/upgrade.ts
30
30
  /**
@@ -71,6 +71,14 @@ var CheckFailedError = class extends Data.TaggedError("CheckFailedError") {
71
71
  return failureDoc(`${CHECK_FAILED_LABEL}\n${indent(this.message)}`);
72
72
  }
73
73
  };
74
+ /** A resolver failure as a `ReadFailure`; a resolver may fail with anything. */
75
+ function readFailure(error) {
76
+ if (error instanceof ResolveError) return error.scope === void 0 ? { message: error.message } : {
77
+ message: error.message,
78
+ scope: error.scope
79
+ };
80
+ return { message: Fmt.errorText(error) };
81
+ }
74
82
  /** Write the rewritten config source back to `file`. */
75
83
  function writeSource(file, next) {
76
84
  return AtomicFile.write(file, next).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot write ${file}` })));
@@ -154,30 +162,45 @@ function resolveGatedVersions(entries, resolver, gate, now, onProgress, workspac
154
162
  return Effect.andThen(report(0, total), () => Effect.forEach([...pairs], ([key, { pkg, fromWorkspace }]) => Effect.gen(function* () {
155
163
  const routed = fromWorkspace && workspace !== void 0 ? workspace : resolver;
156
164
  const needTimes = !fromWorkspace && gate.ageMinutes > 0;
157
- const [vr, times] = yield* Effect.all([routed.versions(pkg).pipe(Effect.result), needTimes ? resolver.times(pkg).pipe(Effect.orElseSucceed(() => ({}))) : Effect.succeed({})], { concurrency: "unbounded" });
165
+ const [vr, tr] = yield* Effect.all([routed.versions(pkg).pipe(Effect.result), needTimes ? resolver.times(pkg).pipe(Effect.result) : Effect.succeed(Result.succeed({}))], { concurrency: "unbounded" });
158
166
  yield* report(++resolved, total);
167
+ const none = [];
159
168
  if (Result.isFailure(vr)) return [
160
169
  key,
161
170
  pkg,
162
- [],
163
- []
171
+ none,
172
+ none,
173
+ readFailure(vr.failure)
164
174
  ];
165
175
  if (fromWorkspace) return [
166
176
  key,
167
177
  pkg,
168
178
  vr.success,
169
- vr.success
179
+ vr.success,
180
+ void 0
181
+ ];
182
+ if (Result.isFailure(tr)) return [
183
+ key,
184
+ pkg,
185
+ none,
186
+ vr.success,
187
+ readFailure(tr.failure)
170
188
  ];
171
189
  return [
172
190
  key,
173
191
  pkg,
174
- [...gate.filterVersions(vr.success, times, pkg, now)],
175
- vr.success
192
+ [...gate.filterVersions(vr.success, tr.success, pkg, now)],
193
+ vr.success,
194
+ void 0
176
195
  ];
177
- }), { concurrency: 12 }).pipe(Effect.map((rows) => ({
196
+ }), { concurrency: 12 }).pipe(Effect.flatMap((rows) => {
197
+ const config = rows.find(([, , , , failure]) => failure?.scope === "config")?.[4];
198
+ return config === void 0 ? Effect.succeed(rows) : Effect.fail(new UpgradeError({ message: `Cannot read the registry configuration: ${config.message}` }));
199
+ }), Effect.map((rows) => ({
178
200
  gated: new Map(rows.map(([key, , gated]) => [key, gated])),
179
201
  raw: new Map(rows.map(([key, , , raw]) => [key, raw])),
180
- unresolved: [...new Set(rows.filter(([, , , raw]) => raw.length === 0).map(([, pkg]) => pkg))]
202
+ unresolved: [...new Set(rows.filter(([, , , raw, failure]) => failure !== void 0 || raw.length === 0).map(([, pkg]) => pkg))],
203
+ causes: new Map(rows.flatMap(([, pkg, , , failure]) => failure === void 0 ? [] : [[pkg, failure.message]]))
181
204
  }))));
182
205
  }
183
206
  /**
@@ -232,7 +255,7 @@ function runUpgrade(opts) {
232
255
  const { source, entries, skipped } = yield* readCatalogSource(opts.file, opts.catalog);
233
256
  const gate = yield* computeGate(source, opts.file, opts.resolver);
234
257
  const versionsByPkg = yield* resolveGatedVersions(entries, opts.resolver, gate, yield* Clock.currentTimeMillis, opts.onProgress, opts.workspaceResolver);
235
- if (versionsByPkg.unresolved.length > 0) return yield* Effect.fail(new UpgradeError({ message: unresolvedMessage(versionsByPkg.unresolved) }));
258
+ if (versionsByPkg.unresolved.length > 0) return yield* Effect.fail(new UpgradeError({ message: unresolvedMessage(versionsByPkg.unresolved, versionsByPkg.causes) }));
236
259
  const skippedChangesets = opts.workspaceResolver?.skippedChangesets() ?? [];
237
260
  if (skippedChangesets.length > 0) return yield* Effect.fail(new UpgradeError({
238
261
  message: skippedChangesetsMessage(skippedChangesets),
@@ -362,9 +385,18 @@ function nothingToUpgradeMessage(totalItems) {
362
385
  *
363
386
  * @internal
364
387
  */
365
- function unresolvedMessage(unresolved) {
366
- const list = unresolved.map((p) => ` ${p}`).join("\n");
367
- return `Could not resolve ${Fmt.plural(unresolved.length, "package")} from the registry — check each name for a typo, or your registry auth:\n${list}`;
388
+ function unresolvedMessage(unresolved, causes = /* @__PURE__ */ new Map()) {
389
+ const head = `Could not resolve ${Fmt.plural(unresolved.length, "package")} from the registry`;
390
+ const advice = "check each name for a typo, or your registry auth";
391
+ const distinct = new Set(unresolved.map((p) => causes.get(p)).filter((c) => c !== void 0));
392
+ const allCaused = unresolved.every((p) => causes.has(p));
393
+ if (allCaused && distinct.size === 1) return `${head} (${[...distinct][0]}):\n${unresolved.map((p) => ` ${p}`).join("\n")}`;
394
+ const list = unresolved.map((p) => {
395
+ const cause = causes.get(p);
396
+ return cause === void 0 ? ` ${p}` : ` ${p}: ${cause}`;
397
+ }).join("\n");
398
+ if (allCaused) return `${head}:\n${list}`;
399
+ return distinct.size === 0 ? `${head} — ${advice}:\n${list}` : `${head}:\n${list}\nA package listed without a cause returned no versions — ${advice}.`;
368
400
  }
369
401
  /** Project walk items to the non-interactive default decisions (latest-in-range, plus peer-only keeps). @internal */
370
402
  function projectDecisions(items, full) {
@@ -413,7 +445,8 @@ function runUpgradePreview(opts) {
413
445
  const items = yield* buildWalkItems(entries, versions.gated).pipe(Effect.mapError((e) => new UpgradeError({ message: e.message })));
414
446
  return {
415
447
  doc: summaryDoc(projectDecisions(items, opts.full)),
416
- unresolved: versions.unresolved
448
+ unresolved: versions.unresolved,
449
+ causes: versions.causes
417
450
  };
418
451
  });
419
452
  }
@@ -609,8 +642,8 @@ function isChangesetFailure(error) {
609
642
  return (error instanceof UpgradeError || error instanceof CheckFailedError) && error.kind === "changeset";
610
643
  }
611
644
  /** Print the unresolved-packages warning to stderr, when there is one. */
612
- function warnUnresolved(unresolved) {
613
- return unresolved.length > 0 ? Doc.print(warningDoc(unresolvedMessage(unresolved)), { stream: "stderr" }) : Effect.void;
645
+ function warnUnresolved(unresolved, causes) {
646
+ return unresolved.length > 0 ? Doc.print(warningDoc(unresolvedMessage(unresolved, causes)), { stream: "stderr" }) : Effect.void;
614
647
  }
615
648
  /**
616
649
  * Resolve every entry's versions, then — for interop catalogs — pre-fetch the
@@ -744,7 +777,7 @@ const upgradeCommand = Command.make("upgrade", {
744
777
  const file = yield* resolveTargetFile(fileOpt);
745
778
  const workspaceResolver = workspaceOf(file);
746
779
  if (preview) {
747
- const { doc, unresolved } = yield* runUpgradePreview({
780
+ const { doc, unresolved, causes } = yield* runUpgradePreview({
748
781
  file,
749
782
  resolver,
750
783
  full,
@@ -752,7 +785,7 @@ const upgradeCommand = Command.make("upgrade", {
752
785
  ...scope
753
786
  });
754
787
  yield* Doc.print(doc);
755
- return yield* warnUnresolved(unresolved);
788
+ return yield* warnUnresolved(unresolved, causes);
756
789
  }
757
790
  if (yes) {
758
791
  const result = yield* withProgress((report) => runUpgrade({
@@ -781,11 +814,11 @@ const upgradeCommand = Command.make("upgrade", {
781
814
  Doc.line(""),
782
815
  Doc.line(Doc.text(note, "muted"))
783
816
  ]);
784
- return yield* warnUnresolved(versions.unresolved);
817
+ return yield* warnUnresolved(versions.unresolved, versions.causes);
785
818
  }
786
819
  const { versions, items, interopByCatalog, interopModels } = yield* withProgress((report) => resolveForWalk(entries, resolver, gate, workspaceResolver, report));
787
820
  if (items.length === 0) {
788
- yield* warnUnresolved(versions.unresolved);
821
+ yield* warnUnresolved(versions.unresolved, versions.causes);
789
822
  return yield* CliMessage.info(nothingToUpgradeMessage(0));
790
823
  }
791
824
  const picked = yield* CliUi.run(walkScreen({
@@ -835,7 +868,7 @@ const upgradeCommand = Command.make("upgrade", {
835
868
  if (!dryRun) yield* applyInteropAndDecisions(file, source, accepted, interopEdits);
836
869
  const changed = countChangedDecisions(nonInteropDecisions.filter((d) => acceptedPkgs.has(d.item.entry.pkg))) + interopChanged;
837
870
  yield* dryRun ? CliMessage.info(`Dry run — no changes written. ${Fmt.plural(changed, "change")} would be applied.`) : CliMessage.success(`Applied ${Fmt.plural(changed, "change")}.`);
838
- yield* warnUnresolved(versions.unresolved);
871
+ yield* warnUnresolved(versions.unresolved, versions.causes);
839
872
  }).pipe(Effect.tapError((error) => isChangesetFailure(error) ? Effect.sync(skippedChangesets.silence) : Effect.void), Effect.ensuring(skippedChangesets.report));
840
873
  }).pipe(Command.withDescription("Upgrade catalog versions in a config file"));
841
874
 
package/cli/cwd.js CHANGED
@@ -1,6 +1,7 @@
1
- import { findWorkspaceFile } from "./workspace-file.js";
2
1
  import { Context, Effect } from "effect";
3
2
  import { join } from "node:path";
3
+ import { locateWorkspaceRootSync } from "@effected/workspaces";
4
+ import { nodeSyncOps } from "@effected/workspaces/node-sync";
4
5
 
5
6
  // src/cli/cwd.ts
6
7
  /**
@@ -11,6 +12,19 @@ import { join } from "node:path";
11
12
  */
12
13
  var WorkingDirectory = class extends Context.Service()("rolldown-pnpm-config/WorkingDirectory") {};
13
14
  /**
15
+ * Walk up from `startDir` to the nearest directory containing a
16
+ * `pnpm-workspace.yaml`; returns the file path or null. A `package.json`
17
+ * `workspaces` field is not a marker here: this tool targets pnpm only.
18
+ *
19
+ * @internal
20
+ */
21
+ function findWorkspaceFile(startDir) {
22
+ return locateWorkspaceRootSync(startDir, {
23
+ ...nodeSyncOps,
24
+ markers: ["pnpm-workspace.yaml"]
25
+ })?.path ?? null;
26
+ }
27
+ /**
14
28
  * The `pnpm-workspace.yaml` a command targets: the explicit path when given,
15
29
  * else the nearest one upward from the working directory, else the working
16
30
  * directory's own (to be created).
@@ -21,4 +35,4 @@ function resolveWorkspacePath(explicit) {
21
35
  return Effect.map(WorkingDirectory, (cwd) => explicit ?? findWorkspaceFile(cwd) ?? join(cwd, "pnpm-workspace.yaml"));
22
36
  }
23
37
 
24
- export { WorkingDirectory, resolveWorkspacePath };
38
+ export { WorkingDirectory, findWorkspaceFile, resolveWorkspacePath };
@@ -1,7 +1,7 @@
1
1
  import { evaluatePluginConfig } from "./evaluate.js";
2
- import { parseWorkspace } from "./workspace-file.js";
3
2
  import { Effect, FileSystem, Predicate } from "effect";
4
3
  import { Fmt } from "@effected/cli-kit";
4
+ import { PnpmWorkspaceFile } from "@effected/pnpm";
5
5
 
6
6
  // src/cli/load-config.ts
7
7
  /**
@@ -26,18 +26,16 @@ function loadConfigAndWorkspace(opts, mkError) {
26
26
  if (errors.length > 0) return yield* Effect.fail(mkError(`Non-literal config values: ${errors.join("; ")}`));
27
27
  const path = opts.workspacePath;
28
28
  const cannotRead = (e) => mkError(`Cannot read or parse ${path}: ${Fmt.errorText(e)}`);
29
- const present = yield* fs.exists(path).pipe(Effect.mapError(cannotRead));
30
- const source = present ? yield* fs.readFileString(path).pipe(Effect.mapError(cannotRead)) : "";
31
- const parsed = present ? yield* Effect.try({
32
- try: () => parseWorkspace(source),
33
- catch: cannotRead
34
- }) : {};
29
+ const source = (yield* fs.exists(path).pipe(Effect.mapError(cannotRead))) ? yield* fs.readFileString(path).pipe(Effect.mapError(cannotRead)) : "";
30
+ const file = yield* PnpmWorkspaceFile.parse(source).pipe(Effect.mapError(cannotRead));
31
+ const parsed = { ...file.value };
35
32
  return {
36
33
  config,
37
34
  localCfg: Predicate.isObject(config.local) ? config.local : void 0,
38
35
  path,
39
36
  parsed,
40
- source
37
+ source,
38
+ file
41
39
  };
42
40
  });
43
41
  }
@@ -1,10 +1,10 @@
1
- import { WORKSPACE_FIELDS } from "./commands/export.js";
1
+ import { WORKSPACE_FIELDS } from "../registry.js";
2
2
  import { buildDiff } from "./diff/build.js";
3
3
  import { renderExportDiff } from "./diff/render.js";
4
4
  import { effectiveManaged, vanillaManaged } from "./effective.js";
5
5
  import { renderSimulated } from "./simulated-view.js";
6
- import { canonicalize } from "./workspace-file.js";
7
6
  import { overlayWorkspace } from "./workspace-overlay.js";
7
+ import { PnpmWorkspaceFile } from "@effected/pnpm";
8
8
 
9
9
  // src/cli/preview-views.ts
10
10
  /**
@@ -23,8 +23,8 @@ function buildPreviewViews(input) {
23
23
  const effective = effectiveManaged(input.managed, input.local, input.parsed, input.manifest, input.rootName);
24
24
  const merged = overlayWorkspace(effective, input.parsed);
25
25
  const vanilla = vanillaManaged(input.managed, input.manifest, input.rootName);
26
- const before = canonicalize(input.parsed);
27
- const changesTree = buildDiff(before, canonicalize(merged), meta);
26
+ const before = PnpmWorkspaceFile.canonicalize(input.parsed);
27
+ const changesTree = buildDiff(before, PnpmWorkspaceFile.canonicalize(merged), meta);
28
28
  return {
29
29
  changes: renderExportDiff(changesTree, { full: false }),
30
30
  full: renderExportDiff(changesTree, { full: true }),
@@ -1,23 +1,32 @@
1
1
  import { isWrappedField } from "../plugin/freeze.js";
2
+ import { FIELD_SCHEMAS } from "../registry.js";
3
+ import { Option, Schema } from "effect";
2
4
 
3
5
  // src/cli/release-age.ts
4
6
  /**
5
7
  * Read a release-age gate from config and combine it with
6
- * {@link @effected/npm#ReleaseAgeGate.combine}. The gate model itself
8
+ * `ReleaseAgeGate.combine`. The gate model itself
7
9
  * (`ReleaseAgeGate`, `PartialReleaseAgeGate`, the age filter, and the
8
- * `@pnpm/matcher` exclude semantics) lives in `@effected/npm`; this module
10
+ * `@pnpm/matcher` exclude semantics) lives in `@effected/pnpm`; this module
9
11
  * only turns a plugin config into a partial contribution (pnpm's own settings
10
12
  * are read by `RegistryResolver.pnpmReleaseAge`, through `PnpmSettings`).
11
13
  */
12
14
  /** Unwrap a managed field that may be a bare value or a `{ value, enforcement }` FieldInput. */
13
15
  const fieldValue = (raw) => isWrappedField(raw) ? raw.value : raw;
16
+ /**
17
+ * The value `freeze` would ship for a release-age field: decoded through its
18
+ * pnpm settings catalog schema, so `"1440"` reads as `1440` here exactly as it
19
+ * does in the build. A value the schema refuses contributes nothing; the build
20
+ * refuses it.
21
+ */
22
+ const decodedField = (field, raw) => raw === void 0 ? void 0 : Option.getOrUndefined(Schema.decodeUnknownOption(FIELD_SCHEMAS[field])(raw));
14
23
  /** Read the release-age gate declared in a statically-evaluated PnpmConfigPlugin config. @internal */
15
24
  function readConfigReleaseAge(config) {
16
25
  if (!config) return null;
17
- const age = fieldValue(config.minimumReleaseAge);
18
- const exc = fieldValue(config.minimumReleaseAgeExclude);
26
+ const age = decodedField("minimumReleaseAge", fieldValue(config.minimumReleaseAge));
27
+ const exc = decodedField("minimumReleaseAgeExclude", fieldValue(config.minimumReleaseAgeExclude));
19
28
  const out = {};
20
- if (typeof age === "number" && Number.isFinite(age)) out.ageMinutes = age;
29
+ if (typeof age === "number") out.ageMinutes = age;
21
30
  if (Array.isArray(exc)) out.exclude = exc.filter((x) => typeof x === "string");
22
31
  return out.ageMinutes === void 0 && out.exclude === void 0 ? null : out;
23
32
  }
package/cli/resolve.js CHANGED
@@ -1,10 +1,9 @@
1
- import { Context, Data, Effect, FileSystem, Layer, Option, Path, Predicate } from "effect";
2
- import { Fmt } from "@effected/cli-kit";
3
- import { PnpmSettings } from "@effected/workspaces";
4
- import { ChildProcess, ChildProcessSpawner } from "effect/process";
1
+ import { Context, Data, DateTime, Effect, FileSystem, Layer, Option, Path } from "effect";
2
+ import { PnpmNpmConfig, PnpmSettings } from "@effected/pnpm";
3
+ import { NpmRegistry } from "@effected/npm";
4
+ import { NpmHttpClient } from "@effected/npm/node";
5
5
 
6
6
  // src/cli/resolve.ts
7
- const Spawner = ChildProcessSpawner.ChildProcessSpawner;
8
7
  /**
9
8
  * Typed failure raised when a package's versions cannot be resolved.
10
9
  *
@@ -13,15 +12,29 @@ const Spawner = ChildProcessSpawner.ChildProcessSpawner;
13
12
  var ResolveError = class extends Data.TaggedError("ResolveError") {};
14
13
  /**
15
14
  * Resolves the published versions of a package from the registry, and the
16
- * release-age gate pnpm itself would apply. The Live implementation shells out
17
- * to `pnpm view` for registry reads, reusing the user's .npmrc, scoped
18
- * registries, auth tokens, proxy and TLS settings, and reads pnpm's own
19
- * settings through `@effected/workspaces`' `PnpmSettings`.
15
+ * release-age gate pnpm itself would apply. The Live implementation reads the
16
+ * registry through `@effected/npm`'s `NpmRegistry`, with the registry, proxy,
17
+ * TLS and credential configuration pnpm 12 would connect with
18
+ * (`@effected/pnpm`'s `PnpmNpmConfig`), and reads pnpm's own settings through
19
+ * `PnpmSettings`.
20
20
  *
21
21
  * @internal
22
22
  */
23
23
  var RegistryResolver = class extends Context.Service()("RegistryResolver") {};
24
24
  /**
25
+ * The production registry client: `NpmRegistry` over `NpmHttpClient`, which
26
+ * applies the npmrc's proxy, bypass, CA, `strict-ssl` and client-certificate
27
+ * settings by pnpm's rules.
28
+ *
29
+ * @internal
30
+ */
31
+ function npmRegistryClient(env) {
32
+ return (config) => NpmRegistry.layer.pipe(Layer.provide(NpmHttpClient.layer(config, {
33
+ env,
34
+ packageManager: "pnpm"
35
+ })));
36
+ }
37
+ /**
25
38
  * Turn pnpm's effective settings into this resolver's partial gate contribution.
26
39
  * `minimumReleaseAge` unset is absent (not an open gate); an empty exclude list
27
40
  * contributes nothing.
@@ -36,105 +49,92 @@ function pnpmGateOf(settings) {
36
49
  if (exclude.length > 0) out.exclude = [...exclude];
37
50
  return out.ageMinutes === void 0 && out.exclude === void 0 ? null : out;
38
51
  }
52
+ /** The `ResolveError` a failed read reports against `pkg`, scoped `"config"` when the configuration failed. */
53
+ const failedRead = (pkg) => (error) => error._tag === "RegistryReadError" ? new ResolveError({
54
+ pkg,
55
+ message: error.message
56
+ }) : new ResolveError({
57
+ pkg,
58
+ message: error.message,
59
+ scope: "config"
60
+ });
39
61
  /**
40
- * Drop pnpm's own notice lines from captured stdout. pnpm prints e.g.
41
- * `[WARN] This project is configured to use 12.5.0… Your current pnpm is v12.4.2`
42
- * (a `packageManager` mismatch) to STDOUT ahead of the `--json` payload, which
43
- * would otherwise make every `pnpm view` unparseable and report each real
44
- * package as an unresolvable typo.
45
- *
46
- * @internal
47
- */
48
- function stripPnpmNotices(stdout) {
49
- return stdout.replace(/^[ \t]*(?:\[WARN\]|\[ERR\]|WARN\b|ERR_PNPM_\w+)[^\n]*\n?/gm, "");
50
- }
51
- /** Parse `pnpm view ... versions --json` stdout: a JSON array, or a single JSON string. @internal */
52
- function parseVersions(pkg, stdout) {
53
- return Effect.try({
54
- try: () => {
55
- const json = JSON.parse(stdout);
56
- if (Array.isArray(json)) return json.map(String);
57
- if (typeof json === "string") return [json];
58
- throw new Error("unexpected shape");
59
- },
60
- catch: () => new ResolveError({
61
- pkg,
62
- message: `Could not parse versions for ${pkg}`
63
- })
64
- });
65
- }
66
- /** Parse a `pnpm view ... --json` object of string values into a string record. */
67
- function parseStringRecord(pkg, stdout, what) {
68
- return Effect.try({
69
- try: () => {
70
- const json = JSON.parse(stdout);
71
- if (!Predicate.isObject(json)) throw new Error("unexpected shape");
72
- const out = {};
73
- for (const [k, v] of Object.entries(json)) out[k] = String(v);
74
- return out;
75
- },
76
- catch: () => new ResolveError({
77
- pkg,
78
- message: `Could not parse ${what} for ${pkg}`
79
- })
80
- });
81
- }
82
- /** Parse `pnpm view <pkg> time --json` stdout: an object of version → ISO date. @internal */
83
- function parseTimes(pkg, stdout) {
84
- return parseStringRecord(pkg, stdout, "times");
85
- }
86
- /** Parse `pnpm view <pkg>@<version> peerDependencies --json`; empty stdout → {}. @internal */
87
- function parsePeerDeps(pkg, stdout) {
88
- const trimmed = stdout.trim();
89
- if (trimmed === "") return Effect.succeed({});
90
- return parseStringRecord(pkg, trimmed, "peerDependencies");
91
- }
92
- /**
93
- * Live RegistryResolver: registry reads through `pnpm view`, the release-age
62
+ * Live RegistryResolver: registry reads through `NpmRegistry`, the release-age
94
63
  * gate through `PnpmSettings`.
95
64
  *
96
- * Registry reads stay on `pnpm view` rather than `@effected/npm`'s
97
- * `NpmRegistry` until the kit honours npmrc `proxy`/`https-proxy`,
98
- * `cafile`/`ca` and `strict-ssl` (spencerbeggs/effected#1307, tracked locally
99
- * in #295): over plain `fetch`, a user behind a corporate proxy or an
100
- * internal CA would fail every lookup that `pnpm view` answers.
65
+ * @remarks
66
+ * The configuration is the one pnpm 12 connects with: `PnpmNpmConfig.load`
67
+ * merges `PNPM_CONFIG_*` variables, `pnpm-workspace.yaml`, the global
68
+ * `config.yaml` and the npmrc files (the workspace root's `.npmrc`, not a
69
+ * member's) in pnpm's precedence, so a `registry:` or `httpsProxy:` in
70
+ * `pnpm-workspace.yaml` applies as it does under `pnpm view`. Every read is
71
+ * routed through `targetFor`, so a scoped registry and its credential apply
72
+ * per package. The configuration,
73
+ * the HTTP client and `PnpmSettings` each load lazily and once
74
+ * (`Effect.cached`): an unreadable npmrc or a malformed `pnpm-workspace.yaml`
75
+ * (or a workspace file pnpm would refuse, such as a registry URL with an
76
+ * environment placeholder) fails the reads that need it, typed as
77
+ * `ResolveError` carrying the cause's message, never layer
78
+ * construction. A package the registry does not know fails `versions` (an
79
+ * unresolvable name is reported, not read as "no versions"); a package whose
80
+ * packument lists no publish times fails `times` with that cause.
101
81
  *
102
- * `PnpmSettings` loads lazily and once (`Effect.cached`), so a malformed
103
- * `pnpm-workspace.yaml` fails only `pnpmReleaseAge`, typed, and never layer
104
- * construction.
82
+ * `client` is the seam for tests: `() => NpmRegistry.layerSeeded(seed)`
83
+ * replaces the network while the npmrc loading and routing stay real. Each
84
+ * call builds a new layer; bind the result to a `const`.
105
85
  *
106
86
  * @internal
107
87
  */
108
- function RegistryResolverLive(options) {
88
+ function RegistryResolverLive(options, client = npmRegistryClient(options.env)) {
109
89
  return Layer.effect(RegistryResolver, Effect.gen(function* () {
110
- const spawner = yield* Spawner;
111
90
  const fs = yield* FileSystem.FileSystem;
112
91
  const path = yield* Path.Path;
113
- const pnpmSettings = yield* Effect.cached(PnpmSettings.load({
92
+ const scope = yield* Effect.scope;
93
+ const platform = (effect) => effect.pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path));
94
+ const pnpmSettings = yield* Effect.cached(platform(PnpmSettings.load({
114
95
  cwd: options.cwd,
115
96
  env: options.env,
116
97
  platform: options.platform
117
- }).pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path)));
118
- /** `pnpm view <spec> <field> --json` stdout, with a spawn failure typed against `pkg`. */
119
- const pnpmView = (pkg, spec, field) => spawner.string(ChildProcess.make("pnpm", [
120
- "view",
121
- spec,
122
- field,
123
- "--json"
124
- ])).pipe(Effect.map(stripPnpmNotices), Effect.mapError((e) => new ResolveError({
125
- pkg,
126
- message: Fmt.errorText(e)
127
98
  })));
99
+ const registry = yield* Effect.cached(Effect.gen(function* () {
100
+ const config = yield* platform(PnpmNpmConfig.load({
101
+ cwd: options.cwd,
102
+ env: options.env,
103
+ platform: options.platform
104
+ }));
105
+ const context = yield* Layer.buildWithScope(client(config), scope).pipe(Effect.provideService(FileSystem.FileSystem, fs));
106
+ return {
107
+ config,
108
+ service: Context.get(context, NpmRegistry)
109
+ };
110
+ }));
111
+ const notFound = (pkg) => new ResolveError({
112
+ pkg,
113
+ message: `${pkg} is not on the registry (check the name for a typo, or your registry auth)`
114
+ });
115
+ const noTimes = (pkg) => new ResolveError({
116
+ pkg,
117
+ message: `publish times unavailable for ${pkg}: the registry lists none`
118
+ });
128
119
  return {
129
- versions: (pkg) => pnpmView(pkg, pkg, "versions").pipe(Effect.flatMap((out) => parseVersions(pkg, out))),
130
- times: (pkg) => pnpmView(pkg, pkg, "time").pipe(Effect.flatMap((out) => parseTimes(pkg, out))),
131
- peerDependencies: (pkg, version) => pnpmView(pkg, `${pkg}@${version}`, "peerDependencies").pipe(Effect.flatMap((out) => parsePeerDeps(pkg, out))),
120
+ versions: (pkg) => registry.pipe(Effect.flatMap(({ config, service }) => service.versions(pkg, config.targetFor(pkg))), Effect.mapError(failedRead(pkg)), Effect.flatMap(Option.match({
121
+ onNone: () => Effect.fail(notFound(pkg)),
122
+ onSome: (v) => Effect.succeed([...v])
123
+ }))),
124
+ times: (pkg) => registry.pipe(Effect.flatMap(({ config, service }) => service.publishTimes(pkg, config.targetFor(pkg))), Effect.mapError(failedRead(pkg)), Effect.flatMap(Option.match({
125
+ onNone: () => Effect.fail(noTimes(pkg)),
126
+ onSome: (entries) => entries.length === 0 ? Effect.fail(noTimes(pkg)) : Effect.succeed(Object.fromEntries(entries.map((e) => [e.version, DateTime.formatIso(e.publishedAt)])))
127
+ }))),
128
+ peerDependencies: (pkg, version) => registry.pipe(Effect.flatMap(({ config, service }) => service.manifest(pkg, version, config.targetFor(pkg))), Effect.mapError(failedRead(pkg)), Effect.map((manifest) => Option.match(manifest, {
129
+ onNone: () => ({}),
130
+ onSome: (m) => ({ ...m.peerDependencies ?? {} })
131
+ }))),
132
132
  pnpmReleaseAge: () => pnpmSettings.pipe(Effect.map(pnpmGateOf), Effect.mapError((e) => new ResolveError({
133
133
  pkg: "pnpm-workspace.yaml",
134
- message: Fmt.errorText(e)
134
+ message: e.message
135
135
  })))
136
136
  };
137
137
  }));
138
138
  }
139
139
 
140
- export { RegistryResolver, RegistryResolverLive, ResolveError, parsePeerDeps, parseTimes, parseVersions, pnpmGateOf, stripPnpmNotices };
140
+ export { RegistryResolver, RegistryResolverLive, ResolveError, npmRegistryClient, pnpmGateOf };
@@ -1,8 +1,8 @@
1
1
  import { scalarText } from "./diff/render.js";
2
2
  import { row, tone } from "./render/tone.js";
3
- import { canonicalize } from "./workspace-file.js";
4
3
  import { Predicate } from "effect";
5
4
  import { Doc } from "@effected/cli-kit";
5
+ import { PnpmWorkspaceFile } from "@effected/pnpm";
6
6
 
7
7
  // src/cli/simulated-view.ts
8
8
  /**
@@ -19,6 +19,7 @@ const STRATEGY_VERB = {
19
19
  mapChildWins: "merge",
20
20
  arrayUnion: "merge",
21
21
  arrayRecordUnion: "merge",
22
+ sectionMerge: "merge",
22
23
  overrides: "merge",
23
24
  peerDependencyRules: "merge",
24
25
  allowBuilds: "merge"
@@ -55,7 +56,7 @@ function flatten(key, value, depth, ann) {
55
56
  * @internal
56
57
  */
57
58
  function renderSimulated(vanilla, manifest) {
58
- const canon = canonicalize(vanilla);
59
+ const canon = PnpmWorkspaceFile.canonicalize(vanilla);
59
60
  return Doc.lines(Object.entries(canon).flatMap(([k, v]) => flatten(k, v, 0, annotation(manifest[k]))));
60
61
  }
61
62
 
package/cli/version.js CHANGED
@@ -6,6 +6,6 @@
6
6
  *
7
7
  * @internal
8
8
  */
9
- const CLI_VERSION = "2.5.2";
9
+ const CLI_VERSION = "3.0.0";
10
10
 
11
11
  export { CLI_VERSION };