@nizza/devkit 0.2.6 → 0.2.8-beta.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.
@@ -10,7 +10,7 @@ async function cleanS3Bucket(s3BucketPath) {
10
10
  }
11
11
  async function copyAssetsToS3(s3BucketPath, projectRoot) {
12
12
  devkit.logger.info('📦 Copying assets to S3 bucket...');
13
- await utils.runCommand(`aws s3 cp ${projectRoot}/dist ${s3BucketPath} --recursive`);
13
+ await utils.runCommand(`aws s3 cp ${projectRoot}/dist ${s3BucketPath} --recursive --exclude "*.map"`);
14
14
  devkit.logger.info('🚚 Assets files copied.');
15
15
  }
16
16
  async function copyTypingsToS3(s3BucketPath, projectRoot) {
@@ -2,52 +2,98 @@
2
2
 
3
3
  var devkit = require('@nx/devkit');
4
4
  var child_process = require('child_process');
5
+ var semver = require('semver');
5
6
  var util = require('util');
6
7
 
7
8
  const execAsync = util.promisify(child_process.exec);
8
9
  /**
9
- * Retrieves the version of a published package with a given name and tag.
10
+ * Checks if an exact package version is already available in the npm registry.
10
11
  *
11
- * @param {string} packageName The name of the package to retrieve the version for.
12
- * @param {string} tag The tag to retrieve the version for.
13
- * @returns The version of the package as a string or an object containing versions for each tag.
14
- */ async function getPublishedPackageVersion(packageName, tag) {
15
- const withTag = tag ? `.${tag}` : ' --json';
16
- const command = `npm view ${packageName} dist-tags${withTag}`;
17
- const { stdout, stderr } = await execAsync(command);
18
- if (stderr) {
19
- devkit.logger.warn(stderr.trim());
12
+ * @param {string} packageName The name of the package to check.
13
+ * @param {string} version The exact version to look for.
14
+ * @returns {Promise<boolean>} True when the version exists in the registry.
15
+ */ async function isVersionPublished(packageName, version) {
16
+ try {
17
+ await execAsync(`npm view ${packageName}@${version} version --json`);
18
+ return true;
19
+ } catch (error) {
20
+ const output = `${error?.stderr ?? ''} ${error?.message ?? ''}`;
21
+ // E404 means that the package or the exact version does not exist yet.
22
+ if (output.includes('E404')) {
23
+ return false;
24
+ }
25
+ devkit.logger.error(`❌ Could not check the npm registry for "${packageName}@${version}".`);
26
+ throw error;
20
27
  }
21
- const published = stdout.trim();
22
- return tag ? published : JSON.parse(published);
23
28
  }
24
29
  /**
25
- * Checks if a package with the given name is already published and returns its version.
30
+ * Checks if the project has commits after the commit that set the current version.
26
31
  *
27
- * @param {string} packageName The name of the package to check for.
28
- * @returns An object containing the published versions of the package and a flag indicating if it is the first version.
29
- */ async function checkPublishedVersion(packageName) {
30
- let publishedVersion;
31
- let isFirstVersion = false;
32
- try {
33
- publishedVersion = await getPublishedPackageVersion(packageName);
34
- } catch (err) {
35
- if (err?.message.includes('code E404')) {
36
- isFirstVersion = true;
37
- devkit.logger.info(`🏁 This is the first version of "${packageName}" package. \n`);
38
- } else {
39
- devkit.logger.error('❌ Error when checking the last published versions \n');
40
- if (err.stderr) {
41
- devkit.logger.error(err.stderr);
42
- }
43
- throw err;
44
- }
32
+ * A published version with changes after its version bump means that there is
33
+ * unpublished work without a changeset.
34
+ *
35
+ * @param {string} workspaceRoot The workspace root.
36
+ * @param {string} projectRoot The project root, relative to the workspace root.
37
+ * @param {string} version The current package version.
38
+ * @returns {Promise<boolean>} True when the project changed after the version bump.
39
+ */ async function hasChangesSinceVersionWasSet(workspaceRoot, projectRoot, version) {
40
+ const packageJsonPath = `${projectRoot}/package.json`;
41
+ const versionNeedle = `"version": "${version}"`;
42
+ const { stdout: versionCommitOutput } = await execAsync(`git log -1 --format=%H -S${JSON.stringify(versionNeedle)} -- ${JSON.stringify(packageJsonPath)}`, {
43
+ cwd: workspaceRoot
44
+ });
45
+ const versionCommit = versionCommitOutput.trim();
46
+ if (!versionCommit) {
47
+ devkit.logger.warn(`⚠️ Could not find the commit that set "${packageJsonPath}" to version ${version}.`);
48
+ return false;
49
+ }
50
+ const { stdout: changesOutput } = await execAsync(`git rev-list --count ${versionCommit}..HEAD -- ${JSON.stringify(projectRoot)}`, {
51
+ cwd: workspaceRoot
52
+ });
53
+ return Number(changesOutput.trim()) > 0;
54
+ }
55
+ /**
56
+ * Decides what to do with a package version before publishing it.
57
+ *
58
+ * The decision keeps the publish step idempotent and blocks versions that can
59
+ * never be published as intended, for example a stable version that was already
60
+ * consumed by a prerelease tag.
61
+ *
62
+ * @param {PublishDecisionInput} input The publish state of the package.
63
+ * @returns {PublishDecision} The action to run and the reason for it.
64
+ */ function getPublishDecision({ packageName, packageVersion, tag, isVersionPublished, hasUnpublishedChanges }) {
65
+ const isPrerelease = semver.prerelease(packageVersion) !== null;
66
+ const packageId = `${packageName}@${packageVersion}`;
67
+ if (tag === 'latest' && isPrerelease) {
68
+ return {
69
+ action: 'error',
70
+ reason: `❌ Refusing to publish prerelease version ${packageId} with the "latest" tag. ` + 'Exit prerelease mode and run "changeset version" on main first.'
71
+ };
72
+ }
73
+ if (!isPrerelease && tag !== 'latest') {
74
+ return hasUnpublishedChanges ? {
75
+ action: 'error',
76
+ reason: `❌ "${packageName}" has unpublished changes, but version ${packageVersion} ` + `is stable and cannot be published with the "${tag}" tag. ` + 'Create a changeset with "pnpm cs" so prerelease mode bumps the version.'
77
+ } : {
78
+ action: 'skip',
79
+ reason: `⏭️ Skipping ${packageId}: the version is stable and has no prerelease suffix. ` + `The "${tag}" tag only accepts prerelease versions. Add a changeset for a new release.`
80
+ };
81
+ }
82
+ if (isVersionPublished) {
83
+ return hasUnpublishedChanges ? {
84
+ action: 'error',
85
+ reason: `❌ ${packageId} is already published on npm, but the project has commits ` + 'after that version. Create a changeset with "pnpm cs" to bump the version.'
86
+ } : {
87
+ action: 'skip',
88
+ reason: `⏭️ ${packageId} is already published on npm. Skipping.`
89
+ };
45
90
  }
46
91
  return {
47
- publishedVersion,
48
- isFirstVersion
92
+ action: 'publish',
93
+ reason: `🚀 Publishing ${packageId} with the "${tag}" tag.`
49
94
  };
50
95
  }
51
96
 
52
- exports.checkPublishedVersion = checkPublishedVersion;
53
- exports.getPublishedPackageVersion = getPublishedPackageVersion;
97
+ exports.getPublishDecision = getPublishDecision;
98
+ exports.hasChangesSinceVersionWasSet = hasChangesSinceVersionWasSet;
99
+ exports.isVersionPublished = isVersionPublished;
@@ -1,15 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  var devkit = require('@nx/devkit');
4
- var semver = require('semver');
5
4
  require('../../shared/logger.cjs');
6
5
  var utils$1 = require('../../shared/utils.cjs');
7
6
  var utils = require('../shared/utils.cjs');
8
7
  var helpers = require('./helpers.cjs');
9
8
 
10
9
  /**
11
- * This is a minimal script to publish package to "npm".
12
- * Need to authenticate with NPM before running this script.
10
+ * Publishes a package to npm.
11
+ *
12
+ * The executor is idempotent: it skips versions that are already published and
13
+ * skips stable versions that cannot use a prerelease tag. It fails when a
14
+ * project has unpublished changes without a new version.
15
+ *
16
+ * Need to authenticate with NPM before running this executor.
13
17
  */ async function runExecutor(opts, ctx) {
14
18
  try {
15
19
  const { tag, dryRun: isDryRun } = opts;
@@ -17,33 +21,30 @@ var helpers = require('./helpers.cjs');
17
21
  // Read the package.json file and extract the name and version.
18
22
  const packageJson = utils$1.getPkgJson(projectRoot);
19
23
  const { name: packageName, version: packageVersion } = packageJson;
20
- // Check if the package has been previously published and get the published version.
21
- const { publishedVersion, isFirstVersion } = await helpers.checkPublishedVersion(packageName);
22
- let greaterThanTagVersion, greaterThanLatestVersion;
23
- if (!isFirstVersion) {
24
- // Check if the package version is greater than the latest published version for the specified tag.
25
- greaterThanTagVersion = publishedVersion?.[tag] ? semver.gt(packageVersion, publishedVersion?.[tag]) : true;
26
- // Check if the package version is greater than the latest published version.
27
- greaterThanLatestVersion = semver.gt(packageVersion, publishedVersion.latest);
28
- console.log(`🔎 package.json version: ${packageVersion}`);
29
- console.log('🔺 published versions:');
30
- Object.entries(publishedVersion).forEach(([k, v])=>console.log(` * ${k}: ${v}`));
31
- console.log('\n');
24
+ // Check the registry and the git history to decide if the version is publishable.
25
+ const versionPublished = await helpers.isVersionPublished(packageName, packageVersion);
26
+ const hasUnpublishedChanges = await helpers.hasChangesSinceVersionWasSet(ctx.root, projectRoot, packageVersion);
27
+ const { action, reason } = helpers.getPublishDecision({
28
+ packageName,
29
+ packageVersion,
30
+ tag,
31
+ isVersionPublished: versionPublished,
32
+ hasUnpublishedChanges
33
+ });
34
+ if (action === 'error') {
35
+ return utils.err(reason);
32
36
  }
33
- // Publish the package if it's the first version or if it's a new version.
34
- const needsPublish = isFirstVersion || greaterThanLatestVersion && greaterThanTagVersion;
35
- if (needsPublish) {
36
- const dryRun = isDryRun ? '--dry-run' : '';
37
- const commandToPublish = `pnpm publish --access public --tag ${tag} --no-git-checks ${dryRun}`;
38
- isDryRun && devkit.logger.info('👀 Skip publish (dry run) \n');
39
- devkit.logger.info(`${commandToPublish} \n`);
40
- // Execute the command to publish the package.
41
- // process.chdir(projectRoot);
42
- await utils.runCommand(commandToPublish, projectRoot);
43
- devkit.logger.info(`\n🚀 Successfully published ${packageName}@${packageVersion}`);
44
- } else {
45
- devkit.logger.warn(`👻 Package version "${packageVersion}" is invalid.`);
37
+ if (action === 'skip') {
38
+ devkit.logger.warn(reason);
39
+ return utils.ok();
46
40
  }
41
+ const dryRun = isDryRun ? '--dry-run' : '';
42
+ const commandToPublish = `pnpm publish --access public --tag ${tag} --no-git-checks ${dryRun}`;
43
+ isDryRun && devkit.logger.info('👀 Skip publish (dry run) \n');
44
+ devkit.logger.info(`${reason}\n${commandToPublish} \n`);
45
+ // Execute the command to publish the package.
46
+ await utils.runCommand(commandToPublish, projectRoot);
47
+ devkit.logger.info(`\n🚀 Successfully published ${packageName}@${packageVersion}`);
47
48
  return utils.ok();
48
49
  } catch (error) {
49
50
  return utils.err(error, '❌ Error when publishing the package');
@@ -2,7 +2,7 @@
2
2
  "$schema": "http://json-schema.org/schema",
3
3
  "version": 2,
4
4
  "title": "Publish executor",
5
- "description": "Automates the process of publishing a package to npm, requiring prior npm authentication. It checks if the current version is greater than both the latest published version and the specified tag version. Supports a dry run mode for testing without actual publication.",
5
+ "description": "Publishes a package to npm after authentication. Skips versions that are already published and versions that cannot use the requested tag. Fails when the project has unpublished changes without a new version. Supports a dry run mode for testing without actual publication.",
6
6
  "type": "object",
7
7
  "properties": {
8
8
  "tag": {
@@ -8,7 +8,7 @@ async function cleanS3Bucket(s3BucketPath) {
8
8
  }
9
9
  async function copyAssetsToS3(s3BucketPath, projectRoot) {
10
10
  logger.info('📦 Copying assets to S3 bucket...');
11
- await runCommand(`aws s3 cp ${projectRoot}/dist ${s3BucketPath} --recursive`);
11
+ await runCommand(`aws s3 cp ${projectRoot}/dist ${s3BucketPath} --recursive --exclude "*.map"`);
12
12
  logger.info('🚚 Assets files copied.');
13
13
  }
14
14
  async function copyTypingsToS3(s3BucketPath, projectRoot) {
@@ -1,50 +1,95 @@
1
1
  import { logger } from '@nx/devkit';
2
2
  import { exec } from 'child_process';
3
+ import semver from 'semver';
3
4
  import { promisify } from 'util';
4
5
 
5
6
  const execAsync = promisify(exec);
6
7
  /**
7
- * Retrieves the version of a published package with a given name and tag.
8
+ * Checks if an exact package version is already available in the npm registry.
8
9
  *
9
- * @param {string} packageName The name of the package to retrieve the version for.
10
- * @param {string} tag The tag to retrieve the version for.
11
- * @returns The version of the package as a string or an object containing versions for each tag.
12
- */ async function getPublishedPackageVersion(packageName, tag) {
13
- const withTag = tag ? `.${tag}` : ' --json';
14
- const command = `npm view ${packageName} dist-tags${withTag}`;
15
- const { stdout, stderr } = await execAsync(command);
16
- if (stderr) {
17
- logger.warn(stderr.trim());
10
+ * @param {string} packageName The name of the package to check.
11
+ * @param {string} version The exact version to look for.
12
+ * @returns {Promise<boolean>} True when the version exists in the registry.
13
+ */ async function isVersionPublished(packageName, version) {
14
+ try {
15
+ await execAsync(`npm view ${packageName}@${version} version --json`);
16
+ return true;
17
+ } catch (error) {
18
+ const output = `${error?.stderr ?? ''} ${error?.message ?? ''}`;
19
+ // E404 means that the package or the exact version does not exist yet.
20
+ if (output.includes('E404')) {
21
+ return false;
22
+ }
23
+ logger.error(`❌ Could not check the npm registry for "${packageName}@${version}".`);
24
+ throw error;
18
25
  }
19
- const published = stdout.trim();
20
- return tag ? published : JSON.parse(published);
21
26
  }
22
27
  /**
23
- * Checks if a package with the given name is already published and returns its version.
28
+ * Checks if the project has commits after the commit that set the current version.
24
29
  *
25
- * @param {string} packageName The name of the package to check for.
26
- * @returns An object containing the published versions of the package and a flag indicating if it is the first version.
27
- */ async function checkPublishedVersion(packageName) {
28
- let publishedVersion;
29
- let isFirstVersion = false;
30
- try {
31
- publishedVersion = await getPublishedPackageVersion(packageName);
32
- } catch (err) {
33
- if (err?.message.includes('code E404')) {
34
- isFirstVersion = true;
35
- logger.info(`🏁 This is the first version of "${packageName}" package. \n`);
36
- } else {
37
- logger.error('❌ Error when checking the last published versions \n');
38
- if (err.stderr) {
39
- logger.error(err.stderr);
40
- }
41
- throw err;
42
- }
30
+ * A published version with changes after its version bump means that there is
31
+ * unpublished work without a changeset.
32
+ *
33
+ * @param {string} workspaceRoot The workspace root.
34
+ * @param {string} projectRoot The project root, relative to the workspace root.
35
+ * @param {string} version The current package version.
36
+ * @returns {Promise<boolean>} True when the project changed after the version bump.
37
+ */ async function hasChangesSinceVersionWasSet(workspaceRoot, projectRoot, version) {
38
+ const packageJsonPath = `${projectRoot}/package.json`;
39
+ const versionNeedle = `"version": "${version}"`;
40
+ const { stdout: versionCommitOutput } = await execAsync(`git log -1 --format=%H -S${JSON.stringify(versionNeedle)} -- ${JSON.stringify(packageJsonPath)}`, {
41
+ cwd: workspaceRoot
42
+ });
43
+ const versionCommit = versionCommitOutput.trim();
44
+ if (!versionCommit) {
45
+ logger.warn(`⚠️ Could not find the commit that set "${packageJsonPath}" to version ${version}.`);
46
+ return false;
47
+ }
48
+ const { stdout: changesOutput } = await execAsync(`git rev-list --count ${versionCommit}..HEAD -- ${JSON.stringify(projectRoot)}`, {
49
+ cwd: workspaceRoot
50
+ });
51
+ return Number(changesOutput.trim()) > 0;
52
+ }
53
+ /**
54
+ * Decides what to do with a package version before publishing it.
55
+ *
56
+ * The decision keeps the publish step idempotent and blocks versions that can
57
+ * never be published as intended, for example a stable version that was already
58
+ * consumed by a prerelease tag.
59
+ *
60
+ * @param {PublishDecisionInput} input The publish state of the package.
61
+ * @returns {PublishDecision} The action to run and the reason for it.
62
+ */ function getPublishDecision({ packageName, packageVersion, tag, isVersionPublished, hasUnpublishedChanges }) {
63
+ const isPrerelease = semver.prerelease(packageVersion) !== null;
64
+ const packageId = `${packageName}@${packageVersion}`;
65
+ if (tag === 'latest' && isPrerelease) {
66
+ return {
67
+ action: 'error',
68
+ reason: `❌ Refusing to publish prerelease version ${packageId} with the "latest" tag. ` + 'Exit prerelease mode and run "changeset version" on main first.'
69
+ };
70
+ }
71
+ if (!isPrerelease && tag !== 'latest') {
72
+ return hasUnpublishedChanges ? {
73
+ action: 'error',
74
+ reason: `❌ "${packageName}" has unpublished changes, but version ${packageVersion} ` + `is stable and cannot be published with the "${tag}" tag. ` + 'Create a changeset with "pnpm cs" so prerelease mode bumps the version.'
75
+ } : {
76
+ action: 'skip',
77
+ reason: `⏭️ Skipping ${packageId}: the version is stable and has no prerelease suffix. ` + `The "${tag}" tag only accepts prerelease versions. Add a changeset for a new release.`
78
+ };
79
+ }
80
+ if (isVersionPublished) {
81
+ return hasUnpublishedChanges ? {
82
+ action: 'error',
83
+ reason: `❌ ${packageId} is already published on npm, but the project has commits ` + 'after that version. Create a changeset with "pnpm cs" to bump the version.'
84
+ } : {
85
+ action: 'skip',
86
+ reason: `⏭️ ${packageId} is already published on npm. Skipping.`
87
+ };
43
88
  }
44
89
  return {
45
- publishedVersion,
46
- isFirstVersion
90
+ action: 'publish',
91
+ reason: `🚀 Publishing ${packageId} with the "${tag}" tag.`
47
92
  };
48
93
  }
49
94
 
50
- export { checkPublishedVersion, getPublishedPackageVersion };
95
+ export { getPublishDecision, hasChangesSinceVersionWasSet, isVersionPublished };
@@ -1,13 +1,17 @@
1
1
  import { logger } from '@nx/devkit';
2
- import semver from 'semver';
3
2
  import '../../shared/logger.mjs';
4
3
  import { getPkgJson } from '../../shared/utils.mjs';
5
- import { getProjectConfig, runCommand, ok, err } from '../shared/utils.mjs';
6
- import { checkPublishedVersion } from './helpers.mjs';
4
+ import { getProjectConfig, err, ok, runCommand } from '../shared/utils.mjs';
5
+ import { isVersionPublished, hasChangesSinceVersionWasSet, getPublishDecision } from './helpers.mjs';
7
6
 
8
7
  /**
9
- * This is a minimal script to publish package to "npm".
10
- * Need to authenticate with NPM before running this script.
8
+ * Publishes a package to npm.
9
+ *
10
+ * The executor is idempotent: it skips versions that are already published and
11
+ * skips stable versions that cannot use a prerelease tag. It fails when a
12
+ * project has unpublished changes without a new version.
13
+ *
14
+ * Need to authenticate with NPM before running this executor.
11
15
  */ async function runExecutor(opts, ctx) {
12
16
  try {
13
17
  const { tag, dryRun: isDryRun } = opts;
@@ -15,33 +19,30 @@ import { checkPublishedVersion } from './helpers.mjs';
15
19
  // Read the package.json file and extract the name and version.
16
20
  const packageJson = getPkgJson(projectRoot);
17
21
  const { name: packageName, version: packageVersion } = packageJson;
18
- // Check if the package has been previously published and get the published version.
19
- const { publishedVersion, isFirstVersion } = await checkPublishedVersion(packageName);
20
- let greaterThanTagVersion, greaterThanLatestVersion;
21
- if (!isFirstVersion) {
22
- // Check if the package version is greater than the latest published version for the specified tag.
23
- greaterThanTagVersion = publishedVersion?.[tag] ? semver.gt(packageVersion, publishedVersion?.[tag]) : true;
24
- // Check if the package version is greater than the latest published version.
25
- greaterThanLatestVersion = semver.gt(packageVersion, publishedVersion.latest);
26
- console.log(`🔎 package.json version: ${packageVersion}`);
27
- console.log('🔺 published versions:');
28
- Object.entries(publishedVersion).forEach(([k, v])=>console.log(` * ${k}: ${v}`));
29
- console.log('\n');
22
+ // Check the registry and the git history to decide if the version is publishable.
23
+ const versionPublished = await isVersionPublished(packageName, packageVersion);
24
+ const hasUnpublishedChanges = await hasChangesSinceVersionWasSet(ctx.root, projectRoot, packageVersion);
25
+ const { action, reason } = getPublishDecision({
26
+ packageName,
27
+ packageVersion,
28
+ tag,
29
+ isVersionPublished: versionPublished,
30
+ hasUnpublishedChanges
31
+ });
32
+ if (action === 'error') {
33
+ return err(reason);
30
34
  }
31
- // Publish the package if it's the first version or if it's a new version.
32
- const needsPublish = isFirstVersion || greaterThanLatestVersion && greaterThanTagVersion;
33
- if (needsPublish) {
34
- const dryRun = isDryRun ? '--dry-run' : '';
35
- const commandToPublish = `pnpm publish --access public --tag ${tag} --no-git-checks ${dryRun}`;
36
- isDryRun && logger.info('👀 Skip publish (dry run) \n');
37
- logger.info(`${commandToPublish} \n`);
38
- // Execute the command to publish the package.
39
- // process.chdir(projectRoot);
40
- await runCommand(commandToPublish, projectRoot);
41
- logger.info(`\n🚀 Successfully published ${packageName}@${packageVersion}`);
42
- } else {
43
- logger.warn(`👻 Package version "${packageVersion}" is invalid.`);
35
+ if (action === 'skip') {
36
+ logger.warn(reason);
37
+ return ok();
44
38
  }
39
+ const dryRun = isDryRun ? '--dry-run' : '';
40
+ const commandToPublish = `pnpm publish --access public --tag ${tag} --no-git-checks ${dryRun}`;
41
+ isDryRun && logger.info('👀 Skip publish (dry run) \n');
42
+ logger.info(`${reason}\n${commandToPublish} \n`);
43
+ // Execute the command to publish the package.
44
+ await runCommand(commandToPublish, projectRoot);
45
+ logger.info(`\n🚀 Successfully published ${packageName}@${packageVersion}`);
45
46
  return ok();
46
47
  } catch (error) {
47
48
  return err(error, '❌ Error when publishing the package');
@@ -2,7 +2,7 @@
2
2
  "$schema": "http://json-schema.org/schema",
3
3
  "version": 2,
4
4
  "title": "Publish executor",
5
- "description": "Automates the process of publishing a package to npm, requiring prior npm authentication. It checks if the current version is greater than both the latest published version and the specified tag version. Supports a dry run mode for testing without actual publication.",
5
+ "description": "Publishes a package to npm after authentication. Skips versions that are already published and versions that cannot use the requested tag. Fails when the project has unpublished changes without a new version. Supports a dry run mode for testing without actual publication.",
6
6
  "type": "object",
7
7
  "properties": {
8
8
  "tag": {
package/executors.json CHANGED
@@ -13,7 +13,7 @@
13
13
  "publish": {
14
14
  "implementation": "./dist/cjs/executors/publish/index.cjs",
15
15
  "schema": "./dist/cjs/executors/publish/schema.json",
16
- "description": "Automates the process of publishing a package to npm, requiring prior npm authentication. It checks if the current version is greater than both the latest published version and the specified tag version. Supports a dry run mode for testing without actual publication"
16
+ "description": "Publishes a package to npm after authentication. Skips versions that are already published and versions that cannot use the requested tag. Fails when the project has unpublished changes without a new version. Supports a dry run mode for testing without actual publication"
17
17
  },
18
18
  "update-executors-file": {
19
19
  "implementation": "./dist/cjs/executors/update-executors-file/index.cjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nizza/devkit",
3
- "version": "0.2.6",
3
+ "version": "0.2.8-beta.0",
4
4
  "type": "module",
5
5
  "main": "dist/cjs/index.cjs",
6
6
  "module": "dist/esm/index.mjs",
package/dist/index.d.ts DELETED
@@ -1,382 +0,0 @@
1
- // Generated by dts-bundle-generator v7.2.0
2
-
3
- import { ExecutorContext } from '@nx/devkit';
4
- import { PreRenderedChunk } from 'rollup';
5
- import { ConfigEnv, LibraryOptions, Plugin, PluginOption, UserConfig, UserConfig as ViteUserConfig, ViteDevServer } from 'vite';
6
- import { InlineConfig as VitestInlineConfig } from 'vitest/node';
7
-
8
- export type ExecutorResponse = {
9
- success: boolean;
10
- };
11
- export interface ExecutorOptions {
12
- s3Bucket: string;
13
- cloudFrontId: string;
14
- cloudFrontInvalidationPaths?: string[];
15
- buildTarget: string;
16
- assetsDir: string;
17
- rootDir?: string;
18
- skipBuild?: boolean;
19
- typings?: boolean;
20
- dryRun?: boolean;
21
- ignoreConfigs?: string[];
22
- }
23
- export function deployExecutor(opts: ExecutorOptions, ctx: ExecutorContext): Promise<ExecutorResponse>;
24
- export interface ExecutorOptions {
25
- }
26
- declare function runExecutor(_opts: ExecutorOptions, ctx: ExecutorContext): Promise<ExecutorResponse>;
27
- export interface ExecutorOptions {
28
- unlink?: boolean;
29
- }
30
- declare function runExecutor(opts: ExecutorOptions, context: ExecutorContext): Promise<ExecutorResponse>;
31
- export interface ExecutorOptions {
32
- tag: string;
33
- dryRun?: boolean;
34
- }
35
- declare function runExecutor(opts: ExecutorOptions, ctx: ExecutorContext): Promise<ExecutorResponse>;
36
- export interface ExecutorOptions {
37
- }
38
- declare function runExecutor(_opts: ExecutorOptions, ctx: ExecutorContext): Promise<ExecutorResponse>;
39
- declare function runExecutor(_opts: any, ctx: ExecutorContext): Promise<ExecutorResponse>;
40
- export interface ExecutorOptions {
41
- packageOrg: string;
42
- rollback?: boolean;
43
- skipLink?: boolean;
44
- }
45
- declare function runExecutor(opts: ExecutorOptions, ctx: ExecutorContext): Promise<ExecutorResponse>;
46
- declare enum LogLevel {
47
- ERROR = 0,
48
- WARN = 1,
49
- INFO = 2,
50
- DEBUG = 3
51
- }
52
- export type ViteConfig = ViteUserConfig & {
53
- test?: VitestInlineConfig;
54
- };
55
- export declare enum ViteMode {
56
- PROD = "production",
57
- DEV = "development",
58
- TEST = "test"
59
- }
60
- /**
61
- * Project stages, it coincides with the target configurations of the project.json of NX.
62
- * @readonly
63
- * @enum {string}
64
- */
65
- export declare enum Stage {
66
- PROD = "prod",
67
- DEV = "dev",
68
- LOCAL = "local"
69
- }
70
- export declare enum ProjectType {
71
- APP = "app",
72
- LIB = "lib",
73
- SCRIPT = "script"
74
- }
75
- export declare enum Flag {
76
- SOURCEMAP = "source-maps",
77
- ANALYZE = "analyze",
78
- VERBOSE = "verbose",
79
- VERBOSE_ALIAS = "v",
80
- HTTPS = "https"
81
- }
82
- export declare enum Target {
83
- BUILD = "build",
84
- PREVIEW = "preview",
85
- SERVE = "serve"
86
- }
87
- /**
88
- * Vite Environment.
89
- *
90
- * @property {ViteMode} mode - Vite mode.
91
- */
92
- export type ViteEnv = ConfigEnv & {
93
- mode: ViteMode;
94
- };
95
- /**
96
- * Externalizing libraries.
97
- *
98
- * @property {boolean} default - React externalizes and other common dependencies,
99
- * this only applies to libraries.
100
- * @property {boolean} glob - Glob expression or list of glob expressions to exclude
101
- * dependencies from the package.json.
102
- */
103
- export type ExternalizeLibs = {
104
- default: boolean;
105
- glob: string | string[];
106
- };
107
- export type ResolveEnvs = {
108
- default: boolean;
109
- local: boolean;
110
- };
111
- /**
112
- * Project configuration.
113
- *
114
- * @property {ProjectType} type - Type of the project.
115
- * @property {string} path - Path of the project.
116
- * @property {string} entry - Path of the file entry point.
117
- * @property {string} name - Name of the project, it is also used to define the name of the library.
118
- * @property {string} port - Server port.
119
- * @property {boolean} debug - Print data purification data.
120
- * @property {boolean} dts - Control if the .d.ts files are generated, by default it is True.
121
- * @property {Partial<ResolveEnvs>} resolveEnvs - Flag for resolving environment.
122
- * @property {boolean} shadowDom - If component is render into shadow dom.
123
- * @property {Partial<ExternalizeLibs>} externalizeLibs - Configuration for externalizing libraries.
124
- * @property {LibraryOptions['fileName']} fileName - Output file name for library.
125
- * @property {string} fileName - Prefix for chunk file name.
126
- * @property {ViteEnv} viteEnv - Vite environment configuration.
127
- * @property {ViteConfig} overrides - Overrides for vite configuration.
128
- */
129
- export interface ProjectConfig {
130
- type: ProjectType;
131
- path: string;
132
- entry?: string;
133
- name?: string;
134
- port?: number;
135
- logLevel?: LogLevel;
136
- dts?: boolean;
137
- resolveEnvs?: Partial<ResolveEnvs>;
138
- shadowDom?: boolean;
139
- externalizeLibs?: Partial<ExternalizeLibs>;
140
- fileName?: LibraryOptions["fileName"];
141
- chunkPrefix?: string;
142
- viteEnv: ViteEnv;
143
- overrides?: UserConfig;
144
- }
145
- export interface ProjectConfigInitialized extends ProjectConfig {
146
- name: string;
147
- fileName: string;
148
- chunkPrefix: string;
149
- logLevel: LogLevel;
150
- overrides: UserConfig;
151
- shadowDom: boolean;
152
- resolveEnvs: ResolveEnvs;
153
- externalizeLibs: ExternalizeLibs;
154
- }
155
- /**
156
- * Vite command details.
157
- * @interface
158
- * @property {Stage} stage - Stage of the project.
159
- * @property {string} target - Command name.
160
- * @property {Record<string, any>} flags - Flags for customize command.
161
- */
162
- export interface ViteCommand {
163
- stage: Stage;
164
- target: string;
165
- flags: Record<string, any>;
166
- }
167
- /**
168
- * Common project configuration.
169
- *
170
- * @property {string} envPrefix - Prefix in lowercase for environment variables and output files.
171
- * @property {boolean} externalizeLibGlob - Glob expression or list of glob expressions to exclude
172
- * dependencies from the package.json.
173
- */
174
- export interface CommonProjectConfig {
175
- envPrefix: string;
176
- externalizeLibGlob?: string | string[];
177
- }
178
- /**
179
- * Config builder context.
180
- *
181
- * @property {CommonProjectConfig} commonConfig - Common configuration for the project.
182
- * @property {ProjectConfigInitialized} projectConfig - Initialized project configuration.
183
- * @property {ViteCommandDetail} viteCmd - Vite command details.
184
- */
185
- export interface Context {
186
- commonConfig: CommonProjectConfig;
187
- projectConfig: ProjectConfigInitialized;
188
- viteCmd: ViteCommand;
189
- localPkgJson: Record<string, any>;
190
- }
191
- /**
192
- * Interface for plugin configuration.
193
- */
194
- export interface PluginConfig {
195
- /**
196
- * Generates plugin(s) based on the provided configuration.
197
- * @param {Context} ctx - The main configuration object.
198
- * @returns {any[]} An array of plugins.
199
- */
200
- generate: (ctx: Context) => any[];
201
- /**
202
- * Condition to determine if the plugin(s) should be included.
203
- * @param {Context} ctx - The main configuration object.
204
- * @returns {boolean} True if the plugin(s) should be included; false otherwise.
205
- */
206
- condition?: (ctx: Context) => boolean;
207
- }
208
- /**
209
- * Deeply merges two objects, combining their properties.
210
- *
211
- * @param {Record<string, any>} v1 - The first object.
212
- * @param {Record<string, any>} v2 - The second object.
213
- * @returns {Record<string, any>} - The merged object.
214
- *
215
- * @example
216
- * const obj1 = { a: 1, b: { c: 2 } };
217
- * const obj2 = { b: { d: 3 } };
218
- * const merged = deepMerge(obj1, obj2); // Outputs: { a: 1, b: { c: 2, d: 3 } }
219
- */
220
- export declare function deepMerge(v1: Record<string, any>, v2: Record<string, any>): Record<string, any>;
221
- /**
222
- * Generates a name for js files.
223
- *
224
- * @param {string} [prefix] - An optional prefix for the chunk name.
225
- * @returns - A function that takes an item and generates a chunk name.
226
- *
227
- * @example
228
- * const generateChunkName = chunkName('prefix');
229
- * const name = generateChunkName({ name: 'example' }); // Outputs: "prefix-example-Aj3_Dk7_2j.js"
230
- */
231
- export declare const chunkName: (prefix?: string) => (x: PreRenderedChunk) => string;
232
- /**
233
- * Returns the given object if the condition is true, otherwise returns null.
234
- *
235
- * @param {any} condition - The condition to evaluate.
236
- * @param {Record<string, any>} obj - The object to return if the condition is true.
237
- * @returns {Record<string, any> | null} - The object or null based on the condition.
238
- *
239
- * @example
240
- * const obj = { a: 1 };
241
- * const result = when(true, obj); // Outputs: { a: 1 }
242
- * const result2 = when(false, obj); // Outputs: {}
243
- */
244
- export declare const when: (condition: any, obj: Record<string, any>) => Record<string, any>;
245
- /**
246
- * Filters and generates plugin configurations based on conditions and the provided context.
247
- *
248
- * @param {Context} ctx - The main configuration object.
249
- * @returns {any[]} - An array of generated plugin configurations.
250
- */
251
- export declare const getPlugins: (ctx: Context, ...pluginConfigs: PluginConfig[]) => PluginOption[];
252
- /**
253
- * Gets the paths to the tsconfig files for all relevant projects.
254
- *
255
- * @returns {string[]} - An array containing paths to tsconfig files for both app and lib projects.
256
- *
257
- * @example
258
- * const projects = {
259
- * 'my-app': {
260
- * type: 'app',
261
- * data: { root: 'apps/my-app' }
262
- * },
263
- * 'my-lib': {
264
- * type: 'lib',
265
- * data: { root: 'libs/my-lib' }
266
- * }
267
- * };
268
- *
269
- * const tsConfigPaths = getTsConfigPaths(projects);
270
- * console.log(tsConfigPaths);
271
- * // Output:
272
- * // ['apps/my-app/tsconfig.app.json', 'libs/my-lib/tsconfig.lib.json']
273
- */
274
- export declare const getNxTsConfigPaths: ({ projectConfig }: Context) => string[];
275
- /**
276
- * Initializes the project configuration with default values.
277
- *
278
- * @example
279
- * const config = { type: ProjectType.APP, path: '/path/to/project', viteEnv: { mode: ViteMode.DEV } };
280
- * const initializedConfig = initializeConfig(config);
281
- */
282
- export declare const initializeConfig: (ccfg: CommonProjectConfig, pcfg: ProjectConfig, localPkgJson: Record<string, any>) => {
283
- viteCmd: ViteCommand;
284
- cfg: ProjectConfigInitialized;
285
- };
286
- /**
287
- * Handles merging configurations and logs any errors.
288
- *
289
- * @param {UserConfig} defaultConfig - The default configuration.
290
- * @param {UserConfig} overrides - The overrides configuration.
291
- * @returns {UserConfig} - The merged configuration.
292
- */
293
- export declare const mergeConfigs: (defaultConfig: UserConfig, overrides: UserConfig) => UserConfig;
294
- /**
295
- * Resolves glob patterns to actual package names found in package.json dependencies.
296
- * This function is used to determine which packages should be treated as external
297
- * in a Rollup or Vite build configuration.
298
- *
299
- * @param {string} path - The base path where package.json is located.
300
- * @param {string | string[]} globs - A glob pattern or an array of glob patterns to match dependencies against.
301
- * @returns {string[]} An array of package names that match the given glob patterns.
302
- *
303
- * @example
304
- * // Example of using `getExternalDependencies` to find all dependencies starting with "my-lib" and "lodash"
305
- * const projectPath = '/path/to/project';
306
- * const globs = ['my-lib*', 'lodash'];
307
- * const externalDependencies = getExternalDependencies(projectPath, globs);
308
- * console.log(externalDependencies);
309
- * // Output might be: ['my-lib/utils', 'my-lib/core', 'lodash']
310
- */
311
- export declare const getExternalDependencies: (path: string, globs?: string | string[]) => string[];
312
- /**
313
- * Generates a string of initials based on the input string,
314
- * following certain rules:
315
- * 1. A word is considered as a sequence of characters
316
- * separated by hyphens.
317
- * 2. If the string contains '@', any characters before
318
- * and including the next '/' are ignored.
319
- * 3. The first character of each word is taken to form
320
- * the initials.
321
- *
322
- * @param {string} input - The input string from which to generate the initials.
323
- * @returns {string} The initials formed by taking the first character
324
- * of each word, after applying the specified rules.
325
- *
326
- * @example
327
- * getInitials("player-script"); // returns "ps"
328
- * getInitials("ssv-admin"); // returns "sa"
329
- * getInitials("@nizza/customize-live"); // returns "cl"
330
- */
331
- export declare function getInitials(input: string): string;
332
- /**
333
- * Retrieves the Vite command details.
334
- *
335
- * @param {ViteMode} mode - The Vite mode.
336
- * @returns {ViteCommand} - The command details.
337
- *
338
- * @example
339
- * const command = getViteCommand(ViteMode.PROD);
340
- * // Outputs: { stage: Stage.PROD, target: 'build', flags: {} }
341
- */
342
- export declare function getViteCommand(mode: ViteMode): ViteCommand;
343
- /**
344
- * Parses the command string to extract flags.
345
- *
346
- * @param {string | undefined} commandString - The command string.
347
- * @returns {Record<string, string>} - The flags extracted from the command string.
348
- *
349
- * @example
350
- * const flags = getViteCmdFlags('nx run core:build --source-maps');
351
- * // Outputs: { 'source-maps: 'true' }
352
- */
353
- export declare function getViteCmdFlags(commandString: string | undefined): Record<string, string>;
354
- /**
355
- * Builds the configuration based on common and project-specific configurations.
356
- *
357
- * @param {CommonProjectConfig} commonConfig - The common configuration.
358
- * @returns - Returns a function that accepts a project configuration and returns the Vite configuration.
359
- */
360
- export declare const createConfigBuilder: (commonConfig: CommonProjectConfig) => (projectConfig: ProjectConfig) => UserConfig;
361
- export interface Execute {
362
- function: (data?: string) => void;
363
- listen: string;
364
- observer: string;
365
- }
366
- export interface ThirdPartyCssInjectPlugin {
367
- topExecutionPriority?: boolean;
368
- execute?: Execute[];
369
- }
370
- /**
371
- * Inject the CSS compiled with JS.
372
- *
373
- * @return {Plugin}
374
- */
375
- export declare function thirdPartyCssInjectPlugin({ topExecutionPriority, execute }?: ThirdPartyCssInjectPlugin | undefined): Plugin;
376
- export declare function injectCssIntoShadowDom(): {
377
- name: string;
378
- configureServer(_server: ViteDevServer): void;
379
- transform(src: string, id: string): void;
380
- };
381
-
382
- export {};