rman 2.32.0 → 2.34.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.
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, RmanConfig, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  import type { CiService } from './services/ci.service.js';
4
4
  /**
@@ -27,7 +27,7 @@ export declare namespace RmanNodeConfig {
27
27
  */
28
28
  interface NpmPublishOptions extends NpmPublishOptionsKeys, ScopedVars {
29
29
  }
30
- interface NpmPublishOptionsKeys extends PublishFilesKeys {
30
+ interface NpmPublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
31
31
  /** Where this package's publishable output lives, relative to its own directory (e.g.
32
32
  * `"build"`). Per-package cascaded, so a root `"[*]"` block can say it once for the whole
33
33
  * repository instead of repeating `publishConfig.directory` in every `package.json` - which
@@ -5,9 +5,10 @@ import { type NpmRelease, type NpmReleases } from '../../publish-targets/npm/npm
5
5
  * npm's answer to `rman deps`: which of a `package.json`'s dependencies have a newer version on the
6
6
  * registry, and which of those can be taken without breaking a rule another dependency states.
7
7
  *
8
- * Only a caret or tilde range on a plain version moves (`^1.2.3`, `~1.2.3`), keeping its prefix. An
9
- * exact version, a compound range (`>=1 <2`, `a || b`), a dist-tag, a URL, an alias and an in-repo
10
- * package are left as they are - but every one of them still counts as a rule the others must keep.
8
+ * Only a caret or tilde range on a plain version moves (`^1.2.3`, `~1.2.3`), keeping its prefix -
9
+ * an npm alias of one too (`npm:@scope/real@^1.2.3`), asked about under the package it names. An
10
+ * exact version, a compound range (`>=1 <2`, `a || b`), a dist-tag, a URL and an in-repo package
11
+ * are left as they are - but every one of them still counts as a rule the others must keep.
11
12
  */
12
13
  export declare class NodeDependencyUpdater implements DependencyUpdater {
13
14
  /** `.rmanrc "deps.types"`'s short spellings, as `npm-check-updates` named them. The field names
@@ -90,10 +91,22 @@ export declare class NodeDependencyUpdater implements DependencyUpdater {
90
91
  /** The newest release `d`'s declarations already allow - what an install picks if `d` does not
91
92
  * move. */
92
93
  protected resolvedDeclared(d: NodeDependencyUpdater.Decision): string | undefined;
93
- /** What `d` declares in `field` once it has moved. */
94
94
  /** Whether `line` names `token` (`name@version`) whole - not `1.2.3` inside `1.2.30`. */
95
95
  protected mentions(line: string, token: string): boolean;
96
+ /** What `d` declares in `field` once it has moved - the range alone, an alias's `npm:<name>@`
97
+ * left off, which is what every rule compares. */
96
98
  protected rangeFor(d: NodeDependencyUpdater.Decision, field: string): string;
99
+ /** The name `d`'s versions are asked under - the package an alias names, else its own. */
100
+ protected sourceOf(d: NodeDependencyUpdater.Decision): string;
101
+ /** What `field` holds once `d` has moved, as the manifest spells it - an alias keeps its
102
+ * `npm:<name>@`. */
103
+ protected writtenFor(d: NodeDependencyUpdater.Decision, field: string): string;
104
+ /** `npm:<name>@<range>`, npm's alias form, as the package it names and the range - or `undefined`
105
+ * for anything else. */
106
+ protected aliasOf(value: string): {
107
+ source: string;
108
+ range: string;
109
+ } | undefined;
97
110
  /** The in-repo packages `pkg` declares a dependency on. */
98
111
  protected siblingsOf(pkg: Package, repoPackages: ReadonlyMap<string, Package>): Package[];
99
112
  protected toEntry(d: NodeDependencyUpdater.Decision): DependencyUpdater.Entry;
@@ -116,8 +129,14 @@ export declare namespace NodeDependencyUpdater {
116
129
  pkg: Package;
117
130
  name: string;
118
131
  settings: DependencyUpdater.Settings;
119
- /** Every field declaring the name, and its range there. */
132
+ /** Every field declaring the name, and its range there - an alias's range, its `npm:<name>@`
133
+ * kept in `aliases`. */
120
134
  fields: Map<string, string>;
135
+ /** The fields declaring the name as an npm alias, and the `npm:<name>@` they write in front. */
136
+ aliases: Map<string, string>;
137
+ /** The package an alias names, whose versions every field of this name is held to - an alias
138
+ * is what installs, so a plain peer range beside it is satisfied by that package. */
139
+ source?: string;
121
140
  /** The fields whose range is rewritten. */
122
141
  movable: string[];
123
142
  /** The fields holding a valid range rman does not rewrite - a pinned version, `>=a <b`. */
@@ -14,10 +14,17 @@ import { parseWorkspaceRange } from './utils/workspace-range.js';
14
14
  * npm's answer to `rman deps`: which of a `package.json`'s dependencies have a newer version on the
15
15
  * registry, and which of those can be taken without breaking a rule another dependency states.
16
16
  *
17
- * Only a caret or tilde range on a plain version moves (`^1.2.3`, `~1.2.3`), keeping its prefix. An
18
- * exact version, a compound range (`>=1 <2`, `a || b`), a dist-tag, a URL, an alias and an in-repo
19
- * package are left as they are - but every one of them still counts as a rule the others must keep.
17
+ * Only a caret or tilde range on a plain version moves (`^1.2.3`, `~1.2.3`), keeping its prefix -
18
+ * an npm alias of one too (`npm:@scope/real@^1.2.3`), asked about under the package it names. An
19
+ * exact version, a compound range (`>=1 <2`, `a || b`), a dist-tag, a URL and an in-repo package
20
+ * are left as they are - but every one of them still counts as a rule the others must keep.
20
21
  */
22
+ /* **Aliases were skipped outright, and silently**: `npm:...` is no semver range, so the field was
23
+ * neither moved nor listed. Measured on `abisena/syncbridge-iomt`, whose host modules are a peer
24
+ * `"@syncbridge/hl7": "^2.0.0"` beside a dev `"npm:@sbext/syncbridge__hl7@^2.0.0"` from a mirror:
25
+ * the alias never appeared, and the peer was asked of npmjs.org under its own name, which stops at
26
+ * 1.2.1 - so a 2.1.0 on the mirror would have read "up to date". The alias is what installs, so the
27
+ * whole name is held to the package it names, and the peer moves with it. */
21
28
  /* **The default is the policy every `.ncurc.yml` in this organization wrote by hand.** Twenty
22
29
  * repositories carried the same `rejectVersion: "/(\|\|)|(&&)|>|<|^[0-9]/"` - no `||`, no `&&`, no
23
30
  * comparator, no bare version - which leaves exactly a `^` or `~` range. Built in, it is a line
@@ -62,7 +69,7 @@ export class NodeDependencyUpdater {
62
69
  const withTime = decisions.some(d => d.settings.minAge > 0);
63
70
  const registry = await this.fetchAll(ctx, decisions, withTime);
64
71
  for (const d of decisions)
65
- this.prepare(d, registry.get(d.name));
72
+ this.prepare(d, registry.get(this.sourceOf(d)));
66
73
  this.resolve(decisions, ctx);
67
74
  return decisions
68
75
  .filter(d => d.wanted || d.unmovable)
@@ -87,8 +94,8 @@ export class NodeDependencyUpdater {
87
94
  if (!originals.has(d.pkg))
88
95
  originals.set(d.pkg, fs.readFileSync(this.manifestFile(d.pkg), 'utf-8'));
89
96
  for (const field of d.movable) {
90
- const deps = d.pkg.manifest.raw[field];
91
- deps[d.name] = this.movablePattern.exec(deps[d.name])[1] + version;
97
+ d.pkg.manifest.raw[field][d.name] =
98
+ (d.aliases.get(field) ?? '') + this.movablePattern.exec(d.fields.get(field))[1] + version;
92
99
  }
93
100
  }
94
101
  for (const pkg of originals.keys())
@@ -142,21 +149,39 @@ export class NodeDependencyUpdater {
142
149
  * tree around it. The `Could not resolve dependency:` line is npm's own verdict - measured on the
143
150
  * `@hookform/resolvers` case it reads `peerOptional effect@"^4.0.0" from @hookform/resolvers@6.0.0`
144
151
  * - so a move it names is the one to hold, and the others it merely passes through stay. That line
145
- * sat past the 20 lines `verify` used to keep, which is why it now keeps them all. */
152
+ * sat past the 20 lines `verify` used to keep, which is why it now keeps them all.
153
+ *
154
+ * **The range form is the other name npm uses**, and missing it misattributed the hold: measured on
155
+ * `abisena/syncbridge-iomt`, the verdict read `dev @syncbridge/syncbuild@"^2.2.0" from the root
156
+ * project`, matched nothing, and every move the output mentioned anywhere was held under that one
157
+ * line - `@syncbridge/testing` included, with syncbuild's reason. */
146
158
  blame(refusal, plan) {
147
159
  const moves = plan.flatMap(entry => {
148
160
  const d = this.planned.get(entry);
149
- return entry.status === 'update' && d ? [{ entry, token: `${d.name}@${d.candidates[d.index]}` }] : [];
161
+ if (entry.status !== 'update' || !d)
162
+ return [];
163
+ /** npm names a move two ways: at the version it resolved (`from x@2.2.0`) and as the range a
164
+ * manifest declares (`dev x@"^2.2.0" from the root project`). */
165
+ const tokens = [
166
+ `${d.name}@${d.candidates[d.index]}`,
167
+ ...d.movable.map(f => `${d.name}@"${this.writtenFor(d, f)}"`),
168
+ ];
169
+ return [{ entry, tokens }];
150
170
  });
171
+ const names = (line, m) => m.tokens.some(t => this.mentions(line, t));
151
172
  const lines = refusal.split('\n').map(line => line.trim());
152
173
  const at = lines.indexOf('Could not resolve dependency:');
153
174
  const verdict = at >= 0 ? lines.slice(at + 1).find(Boolean) : undefined;
154
- const named = verdict ? moves.filter(m => this.mentions(verdict, m.token)) : [];
155
- if (named.length)
156
- return named.map(m => ({ entry: m.entry, reason: `npm cannot install it: ${verdict}` }));
175
+ /** What it conflicts with, when npm says - the half of the verdict that explains it. */
176
+ const conflict = lines.find(l => l.startsWith('Conflicting peer dependency:'));
177
+ const named = verdict ? moves.filter(m => names(verdict, m)) : [];
178
+ if (named.length) {
179
+ const reason = `npm cannot install it: ${verdict}${conflict ? ` - ${conflict}` : ''}`;
180
+ return named.map(m => ({ entry: m.entry, reason }));
181
+ }
157
182
  return moves.flatMap(m => {
158
- const line = lines.find(l => this.mentions(l, m.token));
159
- return line ? [{ entry: m.entry, reason: `npm cannot install it: ${verdict ?? line}` }] : [];
183
+ const line = lines.find(l => names(l, m));
184
+ return line ? [{ entry: m.entry, reason: `npm cannot install it: ${line}` }] : [];
160
185
  });
161
186
  }
162
187
  /** One decision per dependency name `pkg` declares, whether or not it may move - one that may not
@@ -168,8 +193,8 @@ export class NodeDependencyUpdater {
168
193
  const declared = pkg.manifest.raw[field];
169
194
  if (!declared || typeof declared !== 'object')
170
195
  continue;
171
- for (const [name, range] of Object.entries(declared)) {
172
- if (typeof range !== 'string' || inRepo.has(name) || parseWorkspaceRange(range))
196
+ for (const [name, value] of Object.entries(declared)) {
197
+ if (typeof value !== 'string' || inRepo.has(name) || parseWorkspaceRange(value))
173
198
  continue;
174
199
  let d = byName.get(name);
175
200
  if (!d) {
@@ -178,6 +203,7 @@ export class NodeDependencyUpdater {
178
203
  name,
179
204
  settings,
180
205
  fields: new Map(),
206
+ aliases: new Map(),
181
207
  movable: [],
182
208
  fixed: [],
183
209
  wanted: false,
@@ -187,6 +213,17 @@ export class NodeDependencyUpdater {
187
213
  };
188
214
  byName.set(name, d);
189
215
  }
216
+ /** An alias is the range of the package it names: its versions are that package's, so the
217
+ * rules compare the range and the rewrite keeps the `npm:<name>@` in front. */
218
+ /** Two fields aliasing one name to different packages have no one version list to share -
219
+ * the second is left as written, which no rule moves. */
220
+ const parsed = this.aliasOf(value);
221
+ const alias = parsed && (!d.source || d.source === parsed.source) ? parsed : undefined;
222
+ if (alias) {
223
+ d.source = alias.source;
224
+ d.aliases.set(field, `npm:${alias.source}@`);
225
+ }
226
+ const range = alias ? alias.range : value;
190
227
  d.fields.set(field, range);
191
228
  if (kinds && !kinds.includes(field))
192
229
  continue;
@@ -212,13 +249,14 @@ export class NodeDependencyUpdater {
212
249
  async fetchAll(ctx, decisions, withTime) {
213
250
  const floors = new Map();
214
251
  for (const d of decisions) {
252
+ const source = this.sourceOf(d);
215
253
  for (const range of d.fields.values()) {
216
254
  const min = semver.validRange(range) ? semver.minVersion(range)?.version : undefined;
217
255
  if (!min)
218
256
  continue;
219
- const known = floors.get(d.name);
257
+ const known = floors.get(source);
220
258
  if (!known || semver.lt(min, known))
221
- floors.set(d.name, min);
259
+ floors.set(source, min);
222
260
  }
223
261
  }
224
262
  const names = [...floors.keys()];
@@ -480,18 +518,34 @@ export class NodeDependencyUpdater {
480
518
  .filter(v => ranges.every(r => semver.satisfies(v, r)))
481
519
  .sort(semver.rcompare)[0];
482
520
  }
483
- /** What `d` declares in `field` once it has moved. */
484
521
  /** Whether `line` names `token` (`name@version`) whole - not `1.2.3` inside `1.2.30`. */
485
522
  mentions(line, token) {
486
523
  const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
487
524
  return new RegExp(`(^|[\\s"'(])${escaped}(?![\\w.+-])`).test(line);
488
525
  }
526
+ /** What `d` declares in `field` once it has moved - the range alone, an alias's `npm:<name>@`
527
+ * left off, which is what every rule compares. */
489
528
  rangeFor(d, field) {
490
529
  const declared = d.fields.get(field) ?? '';
491
530
  if (d.index < 0 || !d.movable.includes(field))
492
531
  return declared;
493
532
  return this.movablePattern.exec(declared)[1] + d.candidates[d.index];
494
533
  }
534
+ /** The name `d`'s versions are asked under - the package an alias names, else its own. */
535
+ sourceOf(d) {
536
+ return d.source ?? d.name;
537
+ }
538
+ /** What `field` holds once `d` has moved, as the manifest spells it - an alias keeps its
539
+ * `npm:<name>@`. */
540
+ writtenFor(d, field) {
541
+ return (d.aliases.get(field) ?? '') + this.rangeFor(d, field);
542
+ }
543
+ /** `npm:<name>@<range>`, npm's alias form, as the package it names and the range - or `undefined`
544
+ * for anything else. */
545
+ aliasOf(value) {
546
+ const match = /^npm:((?:@[^/@\s]+\/)?[^@\s]+)@(.+)$/.exec(value);
547
+ return match ? { source: match[1], range: match[2] } : undefined;
548
+ }
495
549
  /** The in-repo packages `pkg` declares a dependency on. */
496
550
  siblingsOf(pkg, repoPackages) {
497
551
  const result = new Set();
@@ -522,7 +576,7 @@ export class NodeDependencyUpdater {
522
576
  package: d.pkg,
523
577
  name: d.name,
524
578
  types: [...d.fields.keys()],
525
- current: d.fields.get(d.movable[0]),
579
+ current: (d.aliases.get(d.movable[0]) ?? '') + d.fields.get(d.movable[0]),
526
580
  status: 'up-to-date',
527
581
  latest: d.allowed[0],
528
582
  available: d.available,
@@ -539,7 +593,7 @@ export class NodeDependencyUpdater {
539
593
  const result = {
540
594
  ...entry,
541
595
  status: 'update',
542
- target: this.rangeFor(d, d.movable[0]),
596
+ target: this.writtenFor(d, d.movable[0]),
543
597
  bump: this.sizeOf(d.floor, version),
544
598
  /** What stopped it short of `available`, if anything did - another rule first, since that is
545
599
  * the nearer reason. */
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  /**
4
4
  * **`publish.cloudflare.*`** - this target's own config block, declared beside it and reaching
@@ -9,7 +9,7 @@ import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.in
9
9
  */
10
10
  export interface CloudflarePublishOptions extends CloudflarePublishOptionsKeys, ScopedVars {
11
11
  }
12
- export interface CloudflarePublishOptionsKeys extends PublishFilesKeys {
12
+ export interface CloudflarePublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
13
13
  /**
14
14
  * What the package deploys as: `"pages"` - a directory of static files uploaded to a Pages
15
15
  * project (`wrangler pages deploy`) - or `"workers"` - a Worker, static assets included, as its
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  /**
4
4
  * **`publish.docker.*`** - this target's own config block, declared here rather than centrally.
@@ -15,7 +15,7 @@ export interface DockerPublishOptions extends DockerPublishOptionsKeys, ScopedVa
15
15
  /** Every key here is a **value**, so every one is a `ConfigValue` - this target declares no step,
16
16
  * which is what makes the whole block uniform (see `VersionExtraKeys` for the interface where it
17
17
  * is not). */
18
- export interface DockerPublishOptionsKeys extends PublishFilesKeys {
18
+ export interface DockerPublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
19
19
  /** DockerHub image name/repository - bare (e.g. `"my-app"`) to be prefixed with
20
20
  * `--docker-namespace`/`DOCKERHUB_NAMESPACE`, or already-namespaced (contains a `/`) to use
21
21
  * verbatim. */
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  /**
4
4
  * **`publish.spm.*`** - this target's own config block, reaching `RmanConfig` through the
@@ -6,7 +6,7 @@ import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.in
6
6
  */
7
7
  export interface SpmPublishOptions extends SpmPublishOptionsKeys, ScopedVars {
8
8
  }
9
- export interface SpmPublishOptionsKeys extends PublishFilesKeys {
9
+ export interface SpmPublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
10
10
  /** Who may see the package: `"public"` or `"private"`. spm's own default - a new package is
11
11
  * private - applies when unset. `--spm-access` overrides it. */
12
12
  access?: ConfigValue<'public' | 'private'>;
@@ -2,6 +2,7 @@ import type { CloudflarePublishOptions } from '../builtins/publish-targets/cloud
2
2
  import type { DockerPublishOptions } from '../builtins/publish-targets/docker/docker.target.js';
3
3
  import type { SpmPublishOptions } from '../builtins/publish-targets/spm/spm.target.js';
4
4
  import type { RmanApplication } from '../core/application.js';
5
+ import { type PublishHookKeys } from '../core/interfaces/publish-target.js';
5
6
  import { type RmanConfig } from '../interfaces/rman-config.interface.js';
6
7
  /** Hoisted for `ArgsOf` - see `version.command.ts` and `RmanConfig.ArgsOf` for why. */
7
8
  declare const COMMAND: "publish";
@@ -105,7 +106,7 @@ declare const config: {
105
106
  * ... are not identical` (measured) - so `publish` is contributed once, here, and everything under
106
107
  * it merges into this one interface first.
107
108
  */
108
- export interface PublishExtraKeys extends PublishTargetConfigs {
109
+ export interface PublishExtraKeys extends PublishTargetConfigs, PublishHookKeys {
109
110
  }
110
111
  /** Where a target declares its own `publish.<target>` config block. Augmented, never edited. */
111
112
  export interface PublishTargetConfigs {
@@ -2,8 +2,9 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import readline from 'node:readline/promises';
4
4
  import colors from 'ansi-colors';
5
- import { shipsTo, unknownTargets } from '../core/interfaces/publish-target.js';
5
+ import { shipsTo, unknownTargets, } from '../core/interfaces/publish-target.js';
6
6
  import { registerCommand } from '../interfaces/rman-config.interface.js';
7
+ import { RunService } from '../services/run.service.js';
7
8
  import { assertAllowedBranch, branchGuardOptions, readBranchGuardOptions } from '../utils/branch-guard.js';
8
9
  import { UNCOMMITTED } from '../utils/git.js';
9
10
  import { packageFilterOptions, readPackageFilterOptions } from '../utils/package-filter.js';
@@ -213,6 +214,37 @@ const publishCommand = registerCommand(app => {
213
214
  const outcomes = [];
214
215
  const results = new Map();
215
216
  const publishedBy = new Map();
217
+ const log = args.json ? console.error : console.log;
218
+ /** A hook that failed takes its package out: the entry becomes an `'error'` in the plan the
219
+ * target is handed - so the target leaves it alone - and in the recap. */
220
+ const failHook = (label, plan, i, reason) => {
221
+ plan[i] = { ...plan[i], status: 'error', reason };
222
+ log(colors.red('failed'), colors.gray(`[${label}] `) + colors.cyan(plan[i].package.name), colors.red(reason));
223
+ outcomes.push({ target: label, entry: plan[i] });
224
+ };
225
+ /** `publish.before`, once per package with anything to publish, ahead of every target. */
226
+ const publishing = new Map();
227
+ for (const [target, plan] of plans) {
228
+ for (const e of plan)
229
+ if (e.status === 'publish')
230
+ publishing.set(e.package, [...(publishing.get(e.package) ?? []), target]);
231
+ }
232
+ for (const [pkg, shipsWith] of publishing) {
233
+ const steps = hookSteps(pkg, ['publish'], 'before');
234
+ if (!steps.length)
235
+ continue;
236
+ try {
237
+ await RunService.runHook(pkg, steps, ['publish'], {
238
+ RMAN_PUBLISH_TARGETS: shipsWith.map(t => t.name).join(','),
239
+ });
240
+ }
241
+ catch (e) {
242
+ for (const target of shipsWith) {
243
+ const plan = plans.get(target);
244
+ failHook(target.name, plan, plan.findIndex(x => x.package === pkg), `publish.before: ${e.message}`);
245
+ }
246
+ }
247
+ }
216
248
  let waited = false;
217
249
  for (const [target, plan] of plans) {
218
250
  /** Once, before the first target built from what the others published - see
@@ -224,17 +256,68 @@ const publishCommand = registerCommand(app => {
224
256
  const files = plan.filter(e => e.status === 'publish').flatMap(e => filesFor(e.package, target));
225
257
  const staged = files.length ? PublishFiles.stage(repository.dirname, `[${target.name}]`, files) : undefined;
226
258
  let applied;
259
+ const at = ['publish', target.name];
227
260
  try {
261
+ /** The target's own `before`, with its files already in place - the package as it ships. */
262
+ for (let i = 0; i < plan.length; i++) {
263
+ const entry = plan[i];
264
+ const steps = entry.status === 'publish' ? hookSteps(entry.package, at, 'before') : [];
265
+ if (!steps.length)
266
+ continue;
267
+ try {
268
+ await RunService.runHook(entry.package, steps, at, { RMAN_PUBLISH_TARGET: target.name });
269
+ }
270
+ catch (e) {
271
+ failHook(target.name, plan, i, `publish.${target.name}.before: ${e.message}`);
272
+ }
273
+ }
228
274
  applied = await target.applyPlan(ctx, plan);
229
275
  }
230
276
  finally {
231
277
  staged?.restore();
232
278
  }
279
+ /** The target's own `after`, for each package it did publish. A failure here is reported, but
280
+ * the package is on the registry - the reason says so. */
281
+ for (let i = 0; i < applied.length; i++) {
282
+ const entry = applied[i];
283
+ const planned = plan.find(e => e.package === entry.package);
284
+ const steps = entry.status === 'publish' && planned?.status === 'publish' ? hookSteps(entry.package, at, 'after') : [];
285
+ if (!steps.length)
286
+ continue;
287
+ try {
288
+ await RunService.runHook(entry.package, steps, at, { RMAN_PUBLISH_TARGET: target.name });
289
+ }
290
+ catch (e) {
291
+ applied[i] = {
292
+ ...entry,
293
+ status: 'error',
294
+ reason: `published, but publish.${target.name}.after: ${e.message}`,
295
+ };
296
+ }
297
+ }
233
298
  results.set(target, applied);
234
299
  const done = printApplied(applied, plan, target.name, args.json ? console.error : console.log);
235
300
  outcomes.push(...done);
236
301
  publishedBy.set(target, done.filter(o => o.entry.status === 'publish').map(o => o.entry));
237
302
  }
303
+ /** `publish.after`, once per package every one of whose targets published it. */
304
+ for (const [pkg, shipsWith] of publishing) {
305
+ const done = shipsWith.every(t => results.get(t)?.find(e => e.package === pkg)?.status === 'publish');
306
+ const steps = done ? hookSteps(pkg, ['publish'], 'after') : [];
307
+ if (!steps.length)
308
+ continue;
309
+ try {
310
+ await RunService.runHook(pkg, steps, ['publish'], {
311
+ RMAN_PUBLISH_TARGETS: shipsWith.map(t => t.name).join(','),
312
+ });
313
+ }
314
+ catch (e) {
315
+ const entry = results.get(shipsWith[0]).find(x => x.package === pkg);
316
+ const reason = `published, but publish.after: ${e.message}`;
317
+ log(colors.red('failed'), colors.gray('[publish] ') + colors.cyan(pkg.name), colors.red(reason));
318
+ outcomes.push({ target: 'publish', entry: { ...entry, status: 'error', reason } });
319
+ }
320
+ }
238
321
  printJson(jsonResult(plans, results));
239
322
  if (!args.json)
240
323
  printRecap(outcomes);
@@ -529,3 +612,12 @@ async function confirm(question) {
529
612
  rl.close();
530
613
  }
531
614
  }
615
+ /** The hook steps at `at.<slot>` of `pkg`'s config - `publish.before`, `publish.spm.after` - as a
616
+ * list, refused when one is not a step. */
617
+ function hookSteps(pkg, at, slot) {
618
+ let node = pkg.config;
619
+ for (const key of at)
620
+ node = node && typeof node === 'object' ? node[key] : undefined;
621
+ const value = node && typeof node === 'object' ? node[slot] : undefined;
622
+ return value === undefined ? [] : RunService.normalizeScriptValue(value, `${at.join('.')}.${slot}`, { topo: false });
623
+ }
package/constants.js CHANGED
@@ -1 +1 @@
1
- export const version = '2.32.0';
1
+ export const version = '2.34.0';
@@ -65,6 +65,11 @@ export const STEP_PATHS = [
65
65
  'version.before',
66
66
  'version.exec',
67
67
  'version.after',
68
+ /** `rman publish`'s hooks, around the package's publish and around each target's. */
69
+ 'publish.before',
70
+ 'publish.after',
71
+ 'publish.*.before',
72
+ 'publish.*.after',
68
73
  /**
69
74
  * The step inside a step's **object** form (`{ topo: true, command: buildWithTsc() }`).
70
75
  *
@@ -3,6 +3,7 @@ import type { PackageFilterOptions } from '../../utils/package-filter.js';
3
3
  import type { RmanApplication } from '../application.js';
4
4
  import type { Package } from '../classes/package.js';
5
5
  import type { Repository } from '../classes/repository.js';
6
+ import type { RunStepValue } from './run-step.js';
6
7
  /**
7
8
  * **Where a package's artifact ships, as a contribution.**
8
9
  *
@@ -140,6 +141,23 @@ export declare namespace PublishTarget {
140
141
  };
141
142
  }
142
143
  }
144
+ /**
145
+ * `publish.before` / `publish.after`, and the same pair in every `publish.<target>` block - steps run
146
+ * in the package's directory around its publish, in this order: `publish.before`, then for each
147
+ * target `publish.<target>.before`, the publish, `publish.<target>.after`, and `publish.after` once
148
+ * every target has published it.
149
+ *
150
+ * Only for a package with something to publish - never for one `up-to-date` or skipped, never under
151
+ * `--dry-run`. A failing `before` fails that package (for every target, or for that one) with the
152
+ * step's output as the reason. A shell step sees `RMAN_PUBLISH_TARGET` (that target) or
153
+ * `RMAN_PUBLISH_TARGETS` (all of the package's, comma separated).
154
+ */
155
+ export interface PublishHookKeys {
156
+ /** Run before publishing - `npx spm verify`, `npm run lint`. A string, a function, or a list. */
157
+ before?: RunStepValue | RunStepValue[];
158
+ /** Run after publishing succeeded. */
159
+ after?: RunStepValue | RunStepValue[];
160
+ }
143
161
  /**
144
162
  * `publish.<target>.files` - files copied into the package just before that target publishes it,
145
163
  * and put back afterwards. Every target's block takes it; `publish` itself does the copying.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rman",
3
3
  "description": "Repository manager",
4
- "version": "2.32.0",
4
+ "version": "2.34.0",
5
5
  "author": "Panates",
6
6
  "license": "MIT",
7
7
  "dependencies": {
@@ -999,6 +999,11 @@ const MARKER = /^<!-- rman:documented-up-to ([0-9a-f]{7,40}) -->[ \t]*\r?\n+/m;
999
999
  * - **No file at all** - the whole history, because nothing has been documented. Measured without
1000
1000
  * it: the first `--write` in a repository with a `v1.0.0` tag documented only the commits *after*
1001
1001
  * that tag, and the ones before it were never written anywhere and never would be.
1002
+ * - **A marker naming a commit HEAD does not descend from** - the file came from another repository
1003
+ * without its history, or its branch was rewritten - counts as no marker, with a warning.
1004
+ * Measured on `syncbridge-io/public-modules`: seven changelogs moved in from another repository
1005
+ * carried such a marker, and `version` died at apply time with `fatal: Invalid revision range`
1006
+ * while the plan had looked fine.
1002
1007
  * - **A file with no marker** - one rman did not write, or wrote before markers existed. Fall back
1003
1008
  * to ordinary detection, which is where `catchUpFile` still earns its place: it widens the tag
1004
1009
  * boundary backwards to the file's last commit, so a stale changelog catches up rather than
@@ -1027,8 +1032,15 @@ async function resolveBoundary(git, pkg, changelogFile, options) {
1027
1032
  if (!exists)
1028
1033
  return undefined;
1029
1034
  const marker = MARKER.exec(fs.readFileSync(changelogFile, 'utf-8'));
1030
- if (marker)
1035
+ if (marker && (await git.isAncestor(marker[1])))
1031
1036
  return marker[1];
1037
+ /** A marker naming a commit HEAD does not descend from is a record of somewhere else - the file
1038
+ * was copied in from another repository, or the branch it was written on was rewritten. Read
1039
+ * as "no marker", which is the case built to guess, and said so. */
1040
+ if (marker) {
1041
+ console.error(`warning: ${path.relative(pkg.repository?.dirname ?? process.cwd(), changelogFile)} is documented up to ` +
1042
+ `${marker[1].slice(0, 7)}, which is not in this branch's history - continuing from the package's last release`);
1043
+ }
1032
1044
  }
1033
1045
  return ChangeHashService.detect(git, pkg, {
1034
1046
  from: options.from,
@@ -281,6 +281,15 @@ export declare namespace RunService {
281
281
  * semantics of the shell case too, since `cd x && y` in one process is not the same as two.
282
282
  */
283
283
  export function runLifecycleSlot(pkg: Package, script: string, slot: keyof ScriptSlots, fallback?: RunStepValue[]): Promise<void>;
284
+ /**
285
+ * Runs hook steps from the config alone - a `publish.before`, say - in the package's directory, in
286
+ * order, stopping at the first that fails. Output goes to stderr as it comes, so a command whose
287
+ * stdout is a document keeps it one. Throws with the failed step's last lines.
288
+ *
289
+ * `at` is where the values sit in the config (`['publish', 'spm']`), so a function step is handed
290
+ * the `vars` its own block sees; `env` is added to a shell step's environment.
291
+ */
292
+ export function runHook(pkg: Package, values: RunStepValue[], at: readonly string[], env?: Record<string, string>): Promise<void>;
284
293
  export function getConfig(pkg: Package, script: string): Record<string, unknown>;
285
294
  /**
286
295
  * The context a function step or `if` is handed - see [`RunStepContext`](../core/run-step.ts).
@@ -611,6 +611,48 @@ export class RunService extends Service {
611
611
  }
612
612
  }
613
613
  RunService.runLifecycleSlot = runLifecycleSlot;
614
+ /**
615
+ * Runs hook steps from the config alone - a `publish.before`, say - in the package's directory, in
616
+ * order, stopping at the first that fails. Output goes to stderr as it comes, so a command whose
617
+ * stdout is a document keeps it one. Throws with the failed step's last lines.
618
+ *
619
+ * `at` is where the values sit in the config (`['publish', 'spm']`), so a function step is handed
620
+ * the `vars` its own block sees; `env` is added to a shell step's environment.
621
+ */
622
+ /* **No contributed slots, unlike `runLifecycleSlot`.** A step source maps npm's
623
+ * `pre<script>`/`post<script>`, and for `publish` those are `prepublish`/`postpublish` - which
624
+ * `npm publish` runs itself. Read here too, they would run twice. */
625
+ async function runHook(pkg, values, at, env) {
626
+ for (const value of values) {
627
+ const step = toStep(at[at.length - 1] ?? 'hook', value);
628
+ if (step.if !== undefined &&
629
+ !(await passesIf(pkg.repository, pkg, step.if, pkg.dirname, new Map(), undefined, at))) {
630
+ continue;
631
+ }
632
+ const lines = [];
633
+ const onLine = (line) => {
634
+ lines.push(line);
635
+ process.stderr.write(line + '\n');
636
+ };
637
+ try {
638
+ if (step.run) {
639
+ await step.run(createStepContext(pkg, pkg.dirname, undefined, onLine, undefined, at));
640
+ }
641
+ else {
642
+ await exec(step.command, { cwd: pkg.dirname, app: pkg.repository.app, env, onLine });
643
+ }
644
+ }
645
+ catch (e) {
646
+ const tail = lines
647
+ .map(l => l.trim())
648
+ .filter(Boolean)
649
+ .slice(-4);
650
+ throw new Error(`"${step.label}" failed${e?.message ? ` (${e.message})` : ''}` +
651
+ (tail.length ? ':\n' + tail.map(l => ` ${l}`).join('\n') : ''), { cause: e });
652
+ }
653
+ }
654
+ }
655
+ RunService.runHook = runHook;
614
656
  function getConfig(pkg, script) {
615
657
  const runCfg = pkg.config?.run;
616
658
  const cfg = runCfg && typeof runCfg === 'object' ? runCfg[script] : undefined;
package/utils/git.d.ts CHANGED
@@ -87,6 +87,9 @@ export declare class GitHelper {
87
87
  /** The best common ancestor of `a` and `b` - `undefined` if none exists (unrelated histories,
88
88
  * an invalid ref, ...). */
89
89
  mergeBase(a: string, b: string): Promise<string | undefined>;
90
+ /** Whether `sha` is a commit `ref` descends from - `false` for one this repository does not have
91
+ * at all (history brought over without its commits, a rewritten branch). */
92
+ isAncestor(sha: string, ref?: string): Promise<boolean>;
90
93
  /** The most recent tag matching the glob `pattern` that HEAD actually descends from (unlike
91
94
  * `listTags`, this follows commit ancestry rather than just sorting tag names - the right
92
95
  * choice for a single repo-wide tag scheme, where a package has no tag of its own). */
package/utils/git.js CHANGED
@@ -296,6 +296,17 @@ export class GitHelper {
296
296
  return undefined;
297
297
  }
298
298
  }
299
+ /** Whether `sha` is a commit `ref` descends from - `false` for one this repository does not have
300
+ * at all (history brought over without its commits, a rewritten branch). */
301
+ async isAncestor(sha, ref = 'HEAD') {
302
+ try {
303
+ await execFileAsync('git', ['merge-base', '--is-ancestor', sha, ref], { cwd: this.cwd });
304
+ return true;
305
+ }
306
+ catch {
307
+ return false;
308
+ }
309
+ }
299
310
  /** The most recent tag matching the glob `pattern` that HEAD actually descends from (unlike
300
311
  * `listTags`, this follows commit ancestry rather than just sorting tag names - the right
301
312
  * choice for a single repo-wide tag scheme, where a package has no tag of its own). */