@emulsify/cli 2.4.2 → 2.5.1

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.
Files changed (39) hide show
  1. package/README.md +10 -3
  2. package/dist/handlers/cacheClear.js +5 -6
  3. package/dist/handlers/componentCreate.js +8 -8
  4. package/dist/handlers/componentEjectTemplates.js +22 -20
  5. package/dist/handlers/componentInstall.js +101 -73
  6. package/dist/handlers/componentList.js +51 -4
  7. package/dist/handlers/hofs/withEmulsifySystem.js +3 -1
  8. package/dist/handlers/hofs/withSession.js +8 -0
  9. package/dist/handlers/init.js +144 -132
  10. package/dist/handlers/systemCreate.js +31 -25
  11. package/dist/handlers/systemDetach.js +5 -5
  12. package/dist/handlers/systemInstall.js +62 -55
  13. package/dist/handlers/systemList.js +13 -2
  14. package/dist/index.js +57 -34
  15. package/dist/lib/log.js +21 -24
  16. package/dist/lib/rootHelp.js +30 -5
  17. package/dist/lib/session.js +141 -0
  18. package/dist/schemas/emulsifyProjectConfig.json +11 -0
  19. package/dist/schemas/system.json +1 -0
  20. package/dist/schemas/variant.json +8 -0
  21. package/dist/util/cache/cloneIntoCache.js +25 -8
  22. package/dist/util/cache/copyItemFromCache.js +7 -1
  23. package/dist/util/cache/getCachedItemPath.js +3 -1
  24. package/dist/util/fs/writeToJsonFile.js +4 -1
  25. package/dist/util/getGitRepoNameFromUrl.js +21 -10
  26. package/dist/util/getNonInteractiveGitEnvironment.js +1 -1
  27. package/dist/util/platform/getInitSuccessMessageForPlatform.js +15 -9
  28. package/dist/util/project/componentNpmDependencies.js +169 -0
  29. package/dist/util/project/componentNpmManifest.js +164 -0
  30. package/dist/util/project/generateComponent.js +98 -39
  31. package/dist/util/project/installComponentNpmDependencies.js +197 -0
  32. package/dist/util/project/installDependencies.js +10 -3
  33. package/dist/util/project/installGeneralAssetsFromCache.js +2 -1
  34. package/dist/util/project/resolveComponentTemplate.js +11 -1
  35. package/dist/util/project/rewriteComponentIds.js +69 -0
  36. package/dist/util/prompt/index.js +21 -6
  37. package/dist/util/system/validateSystemConfig.js +13 -27
  38. package/package.json +16 -18
  39. package/dist/handlers/hofs/withProgressBar.js +0 -10
@@ -0,0 +1,141 @@
1
+ import { cancel as renderCancel, intro as renderIntro, note as renderNote, outro as renderOutro, spinner as createSpinner, } from '@clack/prompts';
2
+ import { PROMPT_CANCELLED_EXIT_CODE } from '../util/prompt/index.js';
3
+ const ANSI_PATTERN = new RegExp('[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nqry=><]', 'g');
4
+ let sessionIsOpen = false;
5
+ let sessionMayHaveChanges = false;
6
+ const abortCleanups = new Set();
7
+ export function onAbort(cleanup) {
8
+ abortCleanups.add(cleanup);
9
+ return () => {
10
+ abortCleanups.delete(cleanup);
11
+ };
12
+ }
13
+ export function stripAnsi(value) {
14
+ return value.replace(ANSI_PATTERN, '');
15
+ }
16
+ export function getRendererOutput(stream = process.stdout) {
17
+ const { columns } = stream;
18
+ if (typeof columns === 'number' &&
19
+ (!Number.isFinite(columns) || columns < 40)) {
20
+ stream.columns = 80;
21
+ }
22
+ return stream;
23
+ }
24
+ export function isInteractiveOutput(stream = process.stdout) {
25
+ return stream.isTTY === true;
26
+ }
27
+ export function isSessionOpen() {
28
+ return sessionIsOpen;
29
+ }
30
+ export function markSessionMayHaveChanges() {
31
+ sessionMayHaveChanges = true;
32
+ }
33
+ export function getSessionFailureSummary(cancellation) {
34
+ if (cancellation !== undefined) {
35
+ return sessionMayHaveChanges ? 'Cancelled.' : cancellation;
36
+ }
37
+ return sessionMayHaveChanges ? 'Command failed.' : 'No changes were made.';
38
+ }
39
+ export function startSession(title) {
40
+ if (sessionIsOpen) {
41
+ return;
42
+ }
43
+ sessionIsOpen = true;
44
+ sessionMayHaveChanges = false;
45
+ if (isInteractiveOutput()) {
46
+ renderIntro(title, { output: getRendererOutput() });
47
+ }
48
+ }
49
+ export function finishSession(message) {
50
+ if (!sessionIsOpen) {
51
+ return;
52
+ }
53
+ sessionIsOpen = false;
54
+ if (isInteractiveOutput()) {
55
+ renderOutro(message, { output: getRendererOutput() });
56
+ return;
57
+ }
58
+ if (message) {
59
+ process.stdout.write(`${message}\n`);
60
+ }
61
+ }
62
+ export function cancelSession(message) {
63
+ if (!sessionIsOpen) {
64
+ return;
65
+ }
66
+ sessionIsOpen = false;
67
+ if (isInteractiveOutput()) {
68
+ renderCancel(message, { output: getRendererOutput() });
69
+ return;
70
+ }
71
+ process.stderr.write(`${message}\n`);
72
+ }
73
+ export function note(message, title) {
74
+ if (isInteractiveOutput()) {
75
+ renderNote(message, title, { output: getRendererOutput() });
76
+ return;
77
+ }
78
+ process.stdout.write(`${title ? `${title}\n` : ''}${message}\n`);
79
+ }
80
+ function writeLine(stream, message) {
81
+ if (message) {
82
+ stream.write(`${message}\n`);
83
+ }
84
+ }
85
+ export function spinner(runtime = process) {
86
+ if (isInteractiveOutput(runtime.stdout)) {
87
+ const progress = createSpinner({
88
+ indicator: 'timer',
89
+ output: getRendererOutput(runtime.stdout),
90
+ });
91
+ const abortOnExit = (code) => {
92
+ runtime.off('exit', abortOnExit);
93
+ if (code !== 0)
94
+ return;
95
+ runtime.exitCode = PROMPT_CANCELLED_EXIT_CODE;
96
+ const cleanups = [...abortCleanups];
97
+ abortCleanups.clear();
98
+ for (const cleanup of cleanups) {
99
+ try {
100
+ cleanup();
101
+ }
102
+ catch (error) {
103
+ writeLine(runtime.stderr, String(error));
104
+ }
105
+ }
106
+ };
107
+ const finish = (end) => (message) => {
108
+ runtime.off('exit', abortOnExit);
109
+ end(message);
110
+ };
111
+ return {
112
+ start(message) {
113
+ runtime.off('exit', abortOnExit);
114
+ progress.start(message);
115
+ runtime.on('exit', abortOnExit);
116
+ },
117
+ stop: finish(progress.stop),
118
+ cancel: finish(progress.cancel),
119
+ error: finish(progress.error),
120
+ clear: finish(progress.clear),
121
+ message: progress.message,
122
+ get isCancelled() {
123
+ return progress.isCancelled;
124
+ },
125
+ };
126
+ }
127
+ return {
128
+ start: (message) => writeLine(runtime.stdout, message),
129
+ stop: (message) => writeLine(runtime.stdout, message),
130
+ message: (message) => writeLine(runtime.stdout, message),
131
+ cancel: (message) => writeLine(runtime.stderr, message),
132
+ error: (message) => writeLine(runtime.stderr, message),
133
+ clear: () => undefined,
134
+ isCancelled: false,
135
+ };
136
+ }
137
+ export function resetSessionForTesting() {
138
+ sessionIsOpen = false;
139
+ sessionMayHaveChanges = false;
140
+ abortCleanups.clear();
141
+ }
@@ -95,6 +95,17 @@
95
95
  },
96
96
  "additionalProperties": false
97
97
  },
98
+ "storybook": {
99
+ "type": "object",
100
+ "description": "Configures Emulsify Core's Storybook integration.",
101
+ "properties": {
102
+ "registerDrupalTwigFilters": {
103
+ "type": "boolean",
104
+ "description": "Whether Emulsify Core registers Drupal Twig filters in Storybook."
105
+ }
106
+ },
107
+ "additionalProperties": true
108
+ },
98
109
  "system": {
99
110
  "type": "object",
100
111
  "description": "Contains information about the Emulsify system this project is utilizing",
@@ -21,6 +21,7 @@
21
21
  },
22
22
  "minimumCliVersion": {
23
23
  "type": "string",
24
+ "format": "semver",
24
25
  "description": "Minimum Emulsify CLI version required to use this system"
25
26
  },
26
27
  "structure": {
@@ -80,6 +80,14 @@
80
80
  "items": {
81
81
  "type": "string"
82
82
  }
83
+ },
84
+ "npmDependencies": {
85
+ "type": "object",
86
+ "description": "npm package names mapped to the semver ranges this component needs",
87
+ "additionalProperties": {
88
+ "type": "string",
89
+ "minLength": 1
90
+ }
83
91
  }
84
92
  },
85
93
  "required": ["name", "structure"]
@@ -2,10 +2,13 @@ import { simpleGit } from 'simple-git';
2
2
  import { existsSync, promises as fs } from 'fs';
3
3
  import { basename, dirname, join } from 'path';
4
4
  import { EMULSIFY_CACHE_METADATA_FILE } from '../../lib/constants.js';
5
+ import CliError from '../../lib/CliError.js';
5
6
  import getCachedItemPath from './getCachedItemPath.js';
6
7
  import normalizeRepositoryUrl from './normalizeRepositoryUrl.js';
7
8
  import getNonInteractiveGitEnvironment from '../getNonInteractiveGitEnvironment.js';
8
9
  const REMOTE_REF_LOOKUP_TIMEOUT_MS = 2_000;
10
+ const CLONE_TIMEOUT_MS = 5 * 60 * 1_000;
11
+ const GUARDED_GIT_ENVIRONMENT_KEY = /^(?:GIT_|EDITOR$|PAGER$|PREFIX$|SSH_ASKPASS$|VISUAL$)/i;
9
12
  const TEMP_DIRECTORY_MARKER = '.tmp-';
10
13
  const ABANDONED_TEMP_DIRECTORY_AGE_MS = 24 * 60 * 60 * 1_000;
11
14
  const TEMP_DIRECTORY_SUFFIX_PATTERN = /^\d+-[a-z\d]{6}$/i;
@@ -90,16 +93,22 @@ function getRemoteRefCandidates(checkout) {
90
93
  `refs/tags/${checkout}`,
91
94
  ];
92
95
  }
96
+ function createNonInteractiveGit(timeoutMs) {
97
+ const { GIT_SSH_COMMAND, GIT_TERMINAL_PROMPT, ...environment } = getNonInteractiveGitEnvironment();
98
+ const inheritedEnvironment = Object.fromEntries(Object.entries(environment).filter(([key]) => !GUARDED_GIT_ENVIRONMENT_KEY.test(key.trim())));
99
+ return simpleGit({
100
+ allowEnvironment: ['GIT_SSH_COMMAND', 'GIT_TERMINAL_PROMPT'],
101
+ timeout: { block: timeoutMs, stdOut: false, stdErr: false },
102
+ }).env({
103
+ ...inheritedEnvironment,
104
+ GIT_SSH_COMMAND,
105
+ GIT_TERMINAL_PROMPT,
106
+ });
107
+ }
93
108
  async function getRemoteResolvedRef(repository, checkout) {
94
109
  const remoteRefs = getRemoteRefCandidates(checkout);
95
110
  try {
96
- const git = simpleGit({
97
- timeout: {
98
- block: REMOTE_REF_LOOKUP_TIMEOUT_MS,
99
- stdOut: false,
100
- stdErr: false,
101
- },
102
- }).env(getNonInteractiveGitEnvironment());
111
+ const git = createNonInteractiveGit(REMOTE_REF_LOOKUP_TIMEOUT_MS);
103
112
  const output = await git.listRemote([repository, ...remoteRefs]);
104
113
  const resolvedRefs = new Map();
105
114
  for (const line of output.trim().split(/\r?\n/)) {
@@ -172,7 +181,7 @@ export default function cloneIntoCache(bucket, itemPath, { refresh = false } = {
172
181
  const temporaryDestination = await fs.mkdtemp(`${destination}${TEMP_DIRECTORY_MARKER}${process.pid}-`);
173
182
  let removeTemporaryDestination = true;
174
183
  try {
175
- const git = simpleGit();
184
+ const git = createNonInteractiveGit(CLONE_TIMEOUT_MS);
176
185
  await git.clone(normalizedRepository, temporaryDestination, checkout
177
186
  ? {
178
187
  '--branch': checkout,
@@ -205,6 +214,14 @@ export default function cloneIntoCache(bucket, itemPath, { refresh = false } = {
205
214
  throw error;
206
215
  }
207
216
  }
217
+ catch (error) {
218
+ if (error instanceof Error &&
219
+ 'plugin' in error &&
220
+ error.plugin === 'timeout') {
221
+ throw new CliError(`Cloning repository "${repository}" timed out after ${CLONE_TIMEOUT_MS / 60_000} minutes. Check your network connection and repository access, then retry.`);
222
+ }
223
+ throw error;
224
+ }
208
225
  finally {
209
226
  if (removeTemporaryDestination) {
210
227
  try {
@@ -1,6 +1,7 @@
1
1
  import { copy, remove } from 'fs-extra';
2
2
  import getCachedItemPath from './getCachedItemPath.js';
3
3
  import getEmulsifyConfig from '../project/getEmulsifyConfig.js';
4
+ import rewriteComponentIds from '../project/rewriteComponentIds.js';
4
5
  export default async function copyFileFromCache(bucket, itemPath, destination, force = false) {
5
6
  const emulsifyConfig = await getEmulsifyConfig();
6
7
  const repository = emulsifyConfig?.system?.repository || '';
@@ -14,5 +15,10 @@ export default async function copyFileFromCache(bucket, itemPath, destination, f
14
15
  if (force) {
15
16
  await remove(destination);
16
17
  }
17
- return copy(source, destination);
18
+ await copy(source, destination);
19
+ const [systemName] = itemPath;
20
+ if (bucket !== 'systems' || !systemName || !emulsifyConfig)
21
+ return 0;
22
+ const { count } = await rewriteComponentIds(destination, systemName, emulsifyConfig.project.machineName);
23
+ return count;
18
24
  }
@@ -2,6 +2,7 @@ import { join } from 'path';
2
2
  import { createHash } from 'crypto';
3
3
  import { CACHE_DIR, EMULSIFY_PROJECT_CONFIG_FILE, } from '../../lib/constants.js';
4
4
  import findFileInCurrentPath from '../fs/findFileInCurrentPath.js';
5
+ import safeResolveWithin from '../fs/safeResolveWithin.js';
5
6
  import normalizeRepositoryUrl from './normalizeRepositoryUrl.js';
6
7
  export default function getCachedItemPath({ bucket, itemPath, repository, checkout, }) {
7
8
  const projectPath = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
@@ -15,5 +16,6 @@ export default function getCachedItemPath({ bucket, itemPath, repository, checko
15
16
  repository: normalizedRepository,
16
17
  checkout: normalizedCheckout,
17
18
  });
18
- return join(CACHE_DIR, bucket, createHash('md5').update(identity).digest('hex'), ...itemPath);
19
+ const cacheKey = createHash('md5').update(identity).digest('hex');
20
+ return safeResolveWithin(join(CACHE_DIR, bucket), [cacheKey, ...itemPath], 'Cache item');
19
21
  }
@@ -1,13 +1,16 @@
1
1
  import { promises as fs } from 'fs';
2
2
  import { randomUUID } from 'crypto';
3
3
  import { basename, dirname, join } from 'path';
4
+ import { markSessionMayHaveChanges } from '../../lib/session.js';
4
5
  function createTemporaryPath(path) {
5
6
  return join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
6
7
  }
7
8
  export default async function writeToJsonFile(path, json) {
8
9
  const temporaryPath = createTemporaryPath(path);
9
10
  try {
10
- await fs.writeFile(temporaryPath, JSON.stringify(json, null, 2), {
11
+ const contents = JSON.stringify(json, null, 2);
12
+ markSessionMayHaveChanges();
13
+ await fs.writeFile(temporaryPath, contents, {
11
14
  encoding: 'utf-8',
12
15
  flag: 'wx',
13
16
  flush: true,
@@ -1,9 +1,11 @@
1
1
  import { existsSync } from 'fs';
2
2
  import { basename, isAbsolute, resolve, win32 } from 'path';
3
+ import CliError from '../lib/CliError.js';
3
4
  const fileUriPattern = /^file:\/\//i;
4
5
  const explicitRelativePathPattern = /^\.{1,2}(?:[\\/]|$)/;
5
6
  const uriPattern = /^[a-z][a-z\d+.-]*:\/\//i;
6
7
  const scpLikePattern = /^(?:[^@/\\\s]+@)?[^:/\\\s]+:.+/;
8
+ const repositoryNamePattern = /^[A-Za-z0-9._-]+$/;
7
9
  function isLocalRepository(repository) {
8
10
  if (fileUriPattern.test(repository) ||
9
11
  isAbsolute(repository) ||
@@ -33,20 +35,29 @@ function getLocalRepositoryName(repository) {
33
35
  else {
34
36
  name = basename(resolve(repository));
35
37
  }
36
- return name.endsWith('.git') ? name.slice(0, -4) || undefined : name;
38
+ return name;
37
39
  }
38
40
  export default function getGitRepoNameFromUrl(url) {
39
41
  const repository = url.trim();
40
- if (!repository) {
41
- throw new Error('The repository URL must end in .git.');
42
+ let gitName;
43
+ if (repository && isLocalRepository(repository)) {
44
+ gitName = getLocalRepositoryName(repository);
45
+ if (gitName === undefined) {
46
+ return;
47
+ }
42
48
  }
43
- if (isLocalRepository(repository)) {
44
- return getLocalRepositoryName(repository);
49
+ else {
50
+ const repositoryPath = !uriPattern.test(repository) && scpLikePattern.test(repository)
51
+ ? repository.slice(repository.indexOf(':') + 1)
52
+ : repository;
53
+ gitName = repositoryPath.split('/').at(-1) ?? '';
54
+ if (!gitName.endsWith('.git')) {
55
+ throw new CliError(`The repository URL must end in .git. Received "${url}".`);
56
+ }
45
57
  }
46
- const parts = repository.split('/');
47
- const gitName = parts.at(-1);
48
- if (!gitName.endsWith('.git')) {
49
- throw new Error('The repository URL must end in .git.');
58
+ const name = gitName.endsWith('.git') ? gitName.slice(0, -4) : gitName;
59
+ if (!repositoryNamePattern.test(name) || name === '.' || name === '..') {
60
+ throw new CliError(`Invalid repository name in "${url}".`);
50
61
  }
51
- return gitName.slice(0, -4) || undefined;
62
+ return name;
52
63
  }
@@ -2,6 +2,6 @@ export default function getNonInteractiveGitEnvironment(environment = process.en
2
2
  return {
3
3
  ...environment,
4
4
  GIT_TERMINAL_PROMPT: '0',
5
- GIT_SSH_COMMAND: environment.GIT_SSH_COMMAND || 'ssh -oBatchMode=yes',
5
+ GIT_SSH_COMMAND: `${environment.GIT_SSH_COMMAND || 'ssh'} -oBatchMode=yes`,
6
6
  };
7
7
  }
@@ -1,28 +1,33 @@
1
+ const DRUPAL_INTEGRATION_TITLE = 'Drupal also needs';
1
2
  const DRUPAL_INTEGRATION_MESSAGE = [
2
- 'Detected a Drupal project.',
3
+ 'composer require drupal/emulsify drupal/emulsify_tools',
4
+ 'drush en emulsify_tools -y',
3
5
  '',
4
- 'Install the required Drupal packages with Composer:',
5
- ' composer require drupal/emulsify drupal/emulsify_tools',
6
- ' drush en emulsify_tools -y',
7
- '',
8
- 'The generated Drupal starter uses drupal/emulsify as its base theme and emulsify_tools for Drupal integration, so both packages must exist in the Drupal codebase.',
6
+ 'The generated starter uses drupal/emulsify as its base theme and',
7
+ 'emulsify_tools for Drupal integration, so both packages must exist',
8
+ 'in the Drupal codebase.',
9
9
  ].join('\n');
10
+ const SYSTEM_SELECTION_TITLE = 'Next';
10
11
  const SYSTEM_SELECTION_MESSAGE = [
11
- 'Next, choose a component system:',
12
- ' emulsify system install',
12
+ 'emulsify system install',
13
+ '',
14
+ 'Pick a component system to render with. Nothing renders until one',
15
+ 'is installed.',
13
16
  ].join('\n');
14
17
  export default function getInitSuccessMessageForPlatform(platform, _directory, options = {}) {
15
18
  if (platform === 'drupal') {
16
19
  const messages = [];
17
20
  if (options.includeDrupalInstallReminder) {
18
21
  messages.push({
19
- method: 'warn',
22
+ method: 'info',
20
23
  message: DRUPAL_INTEGRATION_MESSAGE,
24
+ title: DRUPAL_INTEGRATION_TITLE,
21
25
  });
22
26
  }
23
27
  messages.push({
24
28
  method: 'info',
25
29
  message: SYSTEM_SELECTION_MESSAGE,
30
+ title: SYSTEM_SELECTION_TITLE,
26
31
  });
27
32
  return messages;
28
33
  }
@@ -31,6 +36,7 @@ export default function getInitSuccessMessageForPlatform(platform, _directory, o
31
36
  {
32
37
  method: 'info',
33
38
  message: SYSTEM_SELECTION_MESSAGE,
39
+ title: SYSTEM_SELECTION_TITLE,
34
40
  },
35
41
  ];
36
42
  }
@@ -0,0 +1,169 @@
1
+ import { Comparator, minVersion, Range, subset, validRange, } from 'semver';
2
+ import CliError from '../../lib/CliError.js';
3
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/u;
4
+ const DEPENDENCY_SECTIONS = ['dependencies', 'devDependencies'];
5
+ const NON_SATISFYING_SECTIONS = [
6
+ 'optionalDependencies',
7
+ 'peerDependencies',
8
+ ];
9
+ function prereleaseBase({ value, semver }) {
10
+ if (value && semver.prerelease.length > 0) {
11
+ return `${semver.major}.${semver.minor}.${semver.patch}`;
12
+ }
13
+ }
14
+ function intersectComparatorSets(left, right) {
15
+ const leftPrereleases = new Set(left.map(prereleaseBase));
16
+ const rightPrereleases = new Set(right.map(prereleaseBase));
17
+ const comparators = [];
18
+ for (const comparator of [...left, ...right]) {
19
+ const base = prereleaseBase(comparator);
20
+ if (!base || (leftPrereleases.has(base) && rightPrereleases.has(base))) {
21
+ comparators.push(comparator);
22
+ continue;
23
+ }
24
+ if (!comparator.operator)
25
+ return;
26
+ comparators.push(new Comparator(`${comparator.operator.startsWith('>') ? '>=' : '<'}${base}`));
27
+ }
28
+ const exact = comparators.find(({ operator, value }) => !operator && value);
29
+ if (exact) {
30
+ if (comparators.every((comparator) => comparator.test(exact.semver))) {
31
+ return exact.value;
32
+ }
33
+ return;
34
+ }
35
+ let lower;
36
+ let upper;
37
+ for (const comparator of comparators) {
38
+ if (comparator.operator.startsWith('>') &&
39
+ (!lower || !comparator.test(lower.semver))) {
40
+ lower = comparator;
41
+ }
42
+ if (comparator.operator.startsWith('<') &&
43
+ (!upper || !comparator.test(upper.semver))) {
44
+ upper = comparator;
45
+ }
46
+ }
47
+ const intersection = new Range([lower?.value, upper?.value].filter(Boolean).join(' '));
48
+ const minimum = minVersion(intersection);
49
+ let hasMinimum = minimum !== null;
50
+ if (minimum && minimum.patch > Number.MAX_SAFE_INTEGER) {
51
+ const nextRelease = minimum.minor === Number.MAX_SAFE_INTEGER
52
+ ? `${minimum.major + 1}.0.0`
53
+ : `${minimum.major}.${minimum.minor + 1}.0`;
54
+ hasMinimum = intersection.test(nextRelease);
55
+ }
56
+ const upperBase = upper && prereleaseBase(upper);
57
+ if (hasMinimum || (upperBase && intersection.test(`${upperBase}-0`))) {
58
+ return intersection.range || '*';
59
+ }
60
+ }
61
+ function intersectRanges(first, second) {
62
+ const left = new Range(first);
63
+ const right = new Range(second);
64
+ const comparatorOptions = { includePrerelease: true };
65
+ if (!left.intersects(right, comparatorOptions))
66
+ return;
67
+ const alternatives = new Set();
68
+ for (const leftSet of left.set) {
69
+ for (const rightSet of right.set) {
70
+ const intersection = intersectComparatorSets(leftSet, rightSet);
71
+ if (intersection !== undefined)
72
+ alternatives.add(intersection);
73
+ }
74
+ }
75
+ if (alternatives.size === 0)
76
+ return;
77
+ const intersection = [...alternatives].join(' || ');
78
+ const normalized = new Range(intersection).range;
79
+ if (normalized === left.range)
80
+ return first;
81
+ if (normalized === right.range)
82
+ return second;
83
+ return intersection;
84
+ }
85
+ export function collectComponentNpmDependencies(systemName, components, onInvalid) {
86
+ const packages = new Map();
87
+ for (const component of components) {
88
+ for (const [name, range] of Object.entries(component.npmDependencies ?? {})) {
89
+ const context = `System ${JSON.stringify(systemName)}, component ${JSON.stringify(component.name)}, npm package ${JSON.stringify(name)}`;
90
+ try {
91
+ if (name.length > 214 || !PACKAGE_NAME.test(name)) {
92
+ throw new CliError(`${context} has an invalid npm package name.`);
93
+ }
94
+ if (!validRange(range)) {
95
+ throw new CliError(`${context} must use a valid semver range. Received ${JSON.stringify(range)}.`);
96
+ }
97
+ if (subset('*', range)) {
98
+ throw new CliError(`${context} must declare a bounded semver range. Received ${JSON.stringify(range)}, which admits every version.`);
99
+ }
100
+ const requirement = packages.get(name);
101
+ if (!requirement) {
102
+ packages.set(name, {
103
+ range,
104
+ components: new Set([component.name]),
105
+ declarations: new Map([[range, component.name]]),
106
+ });
107
+ continue;
108
+ }
109
+ const intersection = intersectRanges(requirement.range, range);
110
+ if (intersection === undefined) {
111
+ const conflict = [...requirement.declarations].find(([otherRange]) => intersectRanges(otherRange, range) === undefined);
112
+ const competingRequirement = conflict
113
+ ? `${JSON.stringify(conflict[0])} required by component ${JSON.stringify(conflict[1])}`
114
+ : `the combined range ${JSON.stringify(requirement.range)} required by components ${[...requirement.components].map((name) => JSON.stringify(name)).join(', ')}`;
115
+ throw new CliError(`${context} requires ${JSON.stringify(range)}, which conflicts with ${competingRequirement}.`);
116
+ }
117
+ requirement.range = intersection;
118
+ requirement.components.add(component.name);
119
+ requirement.declarations.set(range, component.name);
120
+ }
121
+ catch (error) {
122
+ if (!onInvalid || !(error instanceof CliError))
123
+ throw error;
124
+ onInvalid(error);
125
+ }
126
+ }
127
+ }
128
+ return Array.from(packages, ([name, { range, components }]) => ({
129
+ name,
130
+ range,
131
+ components: [...components],
132
+ }));
133
+ }
134
+ function hasDeclaredPackage(section, name) {
135
+ return (section !== null &&
136
+ typeof section === 'object' &&
137
+ !Array.isArray(section) &&
138
+ Object.hasOwn(section, name));
139
+ }
140
+ export function classifyComponentNpmDependencies(requirements, manifest) {
141
+ return requirements.map((requirement) => {
142
+ const { name } = requirement;
143
+ const nonSatisfyingSections = NON_SATISFYING_SECTIONS.filter((section) => hasDeclaredPackage(manifest[section], name));
144
+ const definition = nonSatisfyingSections.length
145
+ ? { ...requirement, nonSatisfyingSections }
146
+ : requirement;
147
+ if (hasDeclaredPackage(manifest.optionalDependencies, name)) {
148
+ return {
149
+ ...definition,
150
+ status: 'needs-attention',
151
+ declaredRange: manifest.optionalDependencies[name],
152
+ };
153
+ }
154
+ let declared = false;
155
+ for (const section of DEPENDENCY_SECTIONS) {
156
+ const dependencies = manifest[section];
157
+ if (!hasDeclaredPackage(dependencies, name))
158
+ continue;
159
+ declared = true;
160
+ const declaredRange = dependencies[name];
161
+ if (typeof declaredRange !== 'string' ||
162
+ !validRange(declaredRange) ||
163
+ !subset(declaredRange, requirement.range)) {
164
+ return { ...definition, status: 'needs-attention', declaredRange };
165
+ }
166
+ }
167
+ return { ...definition, status: declared ? 'satisfied' : 'missing' };
168
+ });
169
+ }