Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/cli/bin/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
const OCLIF_PATCH = true
const COMMAND_PATCH_ENABLED = true

// Before anything else: on an older Node.js the CLI fails while loading
// (ERR_REQUIRE_ESM), so say which Node.js it needs instead
const nodeError = require('../lib/engines').nodeErrorMessage(require('../package.json'), process.versions.node)
if (nodeError) {
console.error(nodeError)
process.exit(1)
}

// eslint-disable-next-line unicorn/prefer-top-level-await
; (async () => {

Expand All @@ -13,4 +21,4 @@ const COMMAND_PATCH_ENABLED = true

await oclif.execute({ development: false, dir: __dirname })

})()
})()
7 changes: 6 additions & 1 deletion packages/cli/docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,11 @@ Update Commerce Layer CLI.

```sh-session
USAGE
$ commercelayer cli:update [-v <value>]
$ commercelayer cli:update [-v <value> | --latest]

FLAGS
-v, --version=<value> update CLI to a specific version or tag
--latest update CLI to its latest version, a new major included

DESCRIPTION
Update Commerce Layer CLI
Expand All @@ -47,6 +48,10 @@ ALIASES
$ commercelayer latest

EXAMPLES
$ commercelayer cli:update

$ commercelayer cli:update --latest

$ commercelayer cli:update --version=<version-or-tag>
```

Expand Down
92 changes: 83 additions & 9 deletions packages/cli/src/commands/cli/update.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
/* eslint-disable @typescript-eslint/no-misused-promises */

import { exec } from 'node:child_process'
import { promisify } from 'node:util'
import { clColor } from '@commercelayer/cli-core'
import { Command, ux as cliux, Flags } from '@oclif/core'
import { unsupportedNode } from '../../engines'

// import { detect as detectPackageManager } from 'detect-package-manager'


const CLI_PACKAGE = '@commercelayer/cli'

type Release = { name?: string; version?: string; engines?: { node?: string } }


/**
* The version an update installs: by default the latest of the current
* major, a new major only when asked for (--latest, or --version)
*/
const updateTarget = (current: string, flags: { version?: string; latest?: boolean }): string =>
flags.version ?? (flags.latest ? 'latest' : `^${current.split('.')[0]}`)


export default class CliUpdate extends Command {

static description = 'Update Commerce Layer CLI'

static aliases = ['upgrade', 'latest']

static examples = [
'<%= config.bin %> <%= command.id %>',
'<%= config.bin %> <%= command.id %> --latest',
'<%= config.bin %> <%= command.id %> --version=<version-or-tag>',
]

Expand All @@ -21,21 +39,31 @@ export default class CliUpdate extends Command {
char: 'v',
description: 'update CLI to a specific version or tag',
required: false,
})
exclusive: ['latest'],
}),
latest: Flags.boolean({
description: 'update CLI to its latest version, a new major included',
exclusive: ['version'],
}),
}


public async run(): Promise<any> {

const { flags } = await this.parse(CliUpdate)

const version = flags.version ? `@${flags.version}` : ''
// await detectPackageManager().then(pm => this.log)
const current = this.config.version
const target = updateTarget(current, flags)

// A release that doesn't run on this Node.js isn't installed
const release = await this.fetchRelease(target)
const nodeRange = release && unsupportedNode(release, process.versions.node)
if (nodeRange) this.error(`Commerce Layer CLI ${release.version} requires Node.js ${nodeRange} (current: ${process.versions.node}): update Node.js first`)

this.log()
cliux.action.start('Updating Commerce Layer CLI')

const cp = exec(`npm install --location=global @commercelayer/cli${version}`, async (error, stdout, stderr) => {
const cp = exec(`npm install --location=global "${CLI_PACKAGE}@${target}"`, async (error, stdout, stderr) => {

const errorMessage = this.getErrorMessage(error, stdout, stderr)

Expand All @@ -45,7 +73,7 @@ export default class CliUpdate extends Command {
this.error('CLI update failed.')
} else {
cliux.action.stop()
await this.showCliVersion()
await this.showUpdate(current, Boolean(flags.version || flags.latest))
}

})
Expand All @@ -72,11 +100,57 @@ export default class CliUpdate extends Command {
}


private async showCliVersion(): Promise<void> {
/** The npm manifest of a version or tag (none for a range, or when npm can't be reached) */
private async fetchRelease(versionOrTag: string): Promise<Release | undefined> {
if (/^[\^~<>=]/.test(versionOrTag)) {
// A range: its latest version, from the list of versions
const latest = await this.fetchRelease('latest')
return latest?.version?.split('.')[0] === versionOrTag.replace(/^\^/, '') ? latest : undefined
}
return fetch(`https://registry.npmjs.org/${CLI_PACKAGE}/${encodeURIComponent(versionOrTag)}`)
.then(async response => (response.ok ? (await response.json()) as Release : undefined))
.catch(() => undefined)
}


/** The version npm installed: this process still runs the previous one, so config.version is no use */
private async installedVersion(): Promise<string | undefined> {
try {
const verCmd = await this.config.findCommand('cli:version')?.load()
await verCmd?.run([]) // without [] the command uses args of command 'version' and it fails
} catch (_err) { this.log() }
const { stdout } = await promisify(exec)(`npm ls --location=global ${CLI_PACKAGE} --depth=0 --json`)
return JSON.parse(stdout).dependencies?.[CLI_PACKAGE]?.version
} catch {
return undefined
}
}


private async showUpdate(previous: string, explicit: boolean): Promise<void> {

const installed = await this.installedVersion()

this.log()
if (!installed) this.log(`Commerce Layer CLI updated: run ${clColor.cyanBright(`${this.config.bin} version`)} to see its version`)
else if (installed === previous) this.log(`Commerce Layer CLI is up to date: ${clColor.cyanBright(installed)}`)
else this.log(`Commerce Layer CLI updated: ${clColor.dim(previous)} -> ${clColor.green(installed)}`)

// A new major is never installed implicitly: say there is one
if (!explicit) {
const latest = await this.fetchRelease('latest')
const major = Number((installed ?? previous).split('.')[0])
if (latest?.version && (Number(latest.version.split('.')[0]) > major)) {
const nodeRange = unsupportedNode(latest, process.versions.node)
this.log()
this.log(`A new major of Commerce Layer CLI is available: ${clColor.green(latest.version)}`)
if (nodeRange) this.log(`It requires Node.js ${nodeRange} (current: ${process.versions.node})`)
else this.log(`Run ${clColor.cyanBright(`${this.config.bin} cli:update --latest`)} to install it`)
}
}

this.log()

}

}


export { updateTarget }
39 changes: 23 additions & 16 deletions packages/cli/src/commands/plugins/available.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export default class PluginsAvailable extends Command {
cliux.Table.table(availablePlugins, {
key: { header: 'PLUGIN (KEY)', minWidth: 20, get: row => (row.hidden ? clColor.dim : clColor).blueBright(row.name) },
description: { header: 'DESCRIPTION', get: row => (row.hidden ? clColor.dim(row.description) : row.description) },
version: { header: 'VERSION', get: row => clColor.dim(row.version) },
}, {
printLine: clUtil.log,
})
Expand All @@ -62,25 +63,31 @@ type PluginRelease = {
description: string;
enabled: boolean;
hidden?: boolean;
version?: string;
/**
* The versions of the plugin this CLI installs and updates: its major, as
* a range (^N). A new major of the plugin is never installed or updated to
* implicitly: the user asks for it (plugins:install <plugin> --latest),
* or a CLI release raises the range here (a breaking change of the CLI).
*/
version: string;
}

const AvailablePlugins: PluginRelease[] = [
{ name: 'resources', plugin: '@commercelayer/cli-plugin-resources', description: 'CRUD operations on API resources', enabled: true },
{ name: 'seeder', plugin: '@commercelayer/cli-plugin-seeder', description: 'Organization data seeder', enabled: true },
{ name: 'imports', plugin: '@commercelayer/cli-plugin-imports', description: 'Organization imports manager', enabled: true },
{ name: 'webhooks', plugin: '@commercelayer/cli-plugin-webhooks', description: 'Organization webhooks analyzer', enabled: true },
{ name: 'orders', plugin: '@commercelayer/cli-plugin-orders', description: 'Organization orders management', enabled: true },
{ name: 'checkout', plugin: '@commercelayer/cli-plugin-checkout', description: 'Checkout URLs generation', enabled: true },
{ name: 'triggers', plugin: '@commercelayer/cli-plugin-triggers', description: 'Execute actions on resources', enabled: true },
{ name: 'token', plugin: '@commercelayer/cli-plugin-token', description: 'Manage Commerce Layer access tokens', enabled: true },
{ name: 'microstore', plugin: '@commercelayer/cli-plugin-microstore', description: 'Microstore URLs generation', enabled: true },
{ name: 'exports', plugin: '@commercelayer/cli-plugin-exports', description: 'Organization exports manager', enabled: true },
{ name: 'cleanups', plugin: '@commercelayer/cli-plugin-cleanups', description: 'Organization cleanups manager', enabled: true },
{ name: 'tags', plugin: '@commercelayer/cli-plugin-tags', description: 'Manage resources tags', enabled: true },
{ name: 'provisioning', plugin: '@commercelayer/cli-plugin-provisioning', description: 'Add support for Provisioning API', enabled: true },
{ name: 'links', plugin: '@commercelayer/cli-plugin-links', description: 'Manage links to resources', enabled: true },
{ name: 'metrics', plugin: '@commercelayer/cli-plugin-metrics', description: 'Add support for Metrics APIs', enabled: true }
{ name: 'resources', plugin: '@commercelayer/cli-plugin-resources', description: 'CRUD operations on API resources', version: '^7', enabled: true },
{ name: 'seeder', plugin: '@commercelayer/cli-plugin-seeder', description: 'Organization data seeder', version: '^6', enabled: true },
{ name: 'imports', plugin: '@commercelayer/cli-plugin-imports', description: 'Organization imports manager', version: '^5', enabled: true },
{ name: 'webhooks', plugin: '@commercelayer/cli-plugin-webhooks', description: 'Organization webhooks analyzer', version: '^5', enabled: true },
{ name: 'orders', plugin: '@commercelayer/cli-plugin-orders', description: 'Organization orders management', version: '^6', enabled: true },
{ name: 'checkout', plugin: '@commercelayer/cli-plugin-checkout', description: 'Checkout URLs generation', version: '^6', enabled: true },
{ name: 'triggers', plugin: '@commercelayer/cli-plugin-triggers', description: 'Execute actions on resources', version: '^5', enabled: true },
{ name: 'token', plugin: '@commercelayer/cli-plugin-token', description: 'Manage Commerce Layer access tokens', version: '^9', enabled: true },
{ name: 'microstore', plugin: '@commercelayer/cli-plugin-microstore', description: 'Microstore URLs generation', version: '^4', enabled: true },
{ name: 'exports', plugin: '@commercelayer/cli-plugin-exports', description: 'Organization exports manager', version: '^5', enabled: true },
{ name: 'cleanups', plugin: '@commercelayer/cli-plugin-cleanups', description: 'Organization cleanups manager', version: '^4', enabled: true },
{ name: 'tags', plugin: '@commercelayer/cli-plugin-tags', description: 'Manage resources tags', version: '^3', enabled: true },
{ name: 'provisioning', plugin: '@commercelayer/cli-plugin-provisioning', description: 'Add support for Provisioning API', version: '^3', enabled: true },
{ name: 'links', plugin: '@commercelayer/cli-plugin-links', description: 'Manage links to resources', version: '^2', enabled: true },
{ name: 'metrics', plugin: '@commercelayer/cli-plugin-metrics', description: 'Add support for Metrics APIs', version: '^2', enabled: true }
]


Expand Down
43 changes: 43 additions & 0 deletions packages/cli/src/engines.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* The Node.js version a CLI release requires (`engines.node`, as `>=22.13`).
*
* No imports: bin/run.js requires this before anything else, because on an
* older Node.js the CLI fails while loading (ERR_REQUIRE_ESM) with no useful
* message, and the update command checks a release before installing it.
*/

type Manifest = { name?: string; version?: string; engines?: { node?: string } }

const parts = (version: string): number[] => {
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, '').split('.').map(Number)
return [major, minor, patch]
}

/** The minimum version of an engines range of the form `>=x[.y[.z]]`, the only form the CLI uses */
const minimumVersion = (range: string): string | undefined => /^>=\s*(\d+(?:\.\d+){0,2})$/.exec(range.trim())?.[1]

/** Whether a Node.js version satisfies the engines range (true for a range of another form: npm decides) */
const satisfiesNode = (range: string | undefined, node: string): boolean => {
const minimum = range ? minimumVersion(range) : undefined
if (!minimum) return true
const [a, b] = [parts(node), parts(minimum)]
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]
return true
}

/** The Node.js range a release requires when the given Node.js version doesn't satisfy it */
const unsupportedNode = (manifest: Manifest, node: string): string | undefined => {
const range = manifest.engines?.node
return satisfiesNode(range, node) ? undefined : range
}

/** The message bin/run.js prints when the running Node.js is too old for this CLI */
const nodeErrorMessage = (manifest: Manifest, node: string): string | undefined => {
const range = unsupportedNode(manifest, node)
if (!range) return undefined
const major = Number((manifest.version ?? '').split('.')[0])
const previous = major > 1 ? `, or install the previous CLI major, which supports older Node.js versions:\n\n npm install -g ${manifest.name}@${major - 1}` : ''
return `\nCommerce Layer CLI ${manifest.version} requires Node.js ${range} (current: ${node}).\nUpdate Node.js${previous}\n`
}

export { nodeErrorMessage, satisfiesNode, unsupportedNode }
3 changes: 2 additions & 1 deletion packages/cli/src/hooks/init/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ const hook: Hook<'init'> = async (opts) => {

const notifier = updateNotifier({ pkg, updateCheckInterval: (process.env.CL_CLI_UPDATE_NOTIFY ? 0 : 1000 * 60 * 60) })

const updateCommand = /* '{updateCommand}' */ 'commercelayer ' + UPDATE_COMMAND
// cli:update stays on the current major: a new one needs --latest
const updateCommand = /* '{updateCommand}' */ 'commercelayer ' + UPDATE_COMMAND + ((notifier.update?.type === 'major') ? ' --latest' : '')

notifier.notify({
isGlobal: true,
Expand Down
Loading
Loading