semver#valid TypeScript Examples

The following examples show how to use semver#valid. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dependency-version-compare.ts    From eslint-config-kit with MIT License 6 votes vote down vote up
export function toVersion(versionOrRange: string): string {
  if (valid(versionOrRange)) {
    return versionOrRange
  }

  if (validRange(versionOrRange)) {
    const versionObject = minVersion(versionOrRange)
    if (!versionObject) throw new InvalidVersionError()
    return versionObject.version
  }

  throw new InvalidVersionError()
}
Example #2
Source File: dependency-version-compare.ts    From eslint-config-kit with MIT License 6 votes vote down vote up
function compare(
  versionOrRange: string,
  target: string,
  sign: '<' | '>'
): boolean {
  if (valid(versionOrRange)) {
    return satisfies(versionOrRange, sign + target)
  }

  if (validRange(versionOrRange)) {
    const matches = satisfies(target, versionOrRange)
    return subset(versionOrRange, sign + target) || (sign === '>' && matches)
  }

  throw new InvalidVersionError()
}
Example #3
Source File: platform.ts    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
isAboveIOS14 = () => {
  if (Platform.OS === 'ios') {
    const platformVer = valid(coerce(Platform.Version.toString()));
    if (platformVer) {
      return gte(platformVer, '14.0.0');
    }
  }
  return false;
}
Example #4
Source File: deprecate-version.ts    From react-celo with MIT License 5 votes vote down vote up
void (async function () {
  start();
  const prompts: RevalidatorSchema[] = [
    {
      name: 'version',
      description: green('Which sdk version do you want to deprecate?'),
    },
    {
      name: 'message',
      description: green('Reason for deprecation:'),
    },
  ];
  const { version, message } = await get<{ version: string; message: string }>(
    prompts
  );
  if (!valid(version)) {
    console.error(red('Invalid version'));
    process.exit(1);
  }
  const sdkPackagePaths = findPackagePaths(
    path.join(__dirname, '..', 'packages', 'sdk')
  );
  const sdkJsons = sdkPackagePaths.map(readPackageJson);
  const otpPrompt = [
    {
      name: 'newOtp',
      description: green(`Enter 2FA code`),
    },
  ];

  let otp = '';
  for (const sdkJson of sdkJsons) {
    let { newOtp } = await get<{ newOtp: string }>(otpPrompt);
    if (!newOtp) {
      newOtp = otp;
    } else {
      otp = newOtp;
    }
    const buffer = child_process.execSync(
      `npm info ${sdkJson.name} versions --json`
    );
    const versions = JSON.parse(buffer.toString()) as string[];
    if (!versions.includes(version)) {
      console.log(
        yellow(`Version ${version} does not exist for ${sdkJson.name}.`)
      );
    } else {
      try {
        child_process.execSync(
          `npm deprecate ${sdkJson.name}@${version} '${message}' --otp ${newOtp}`
        );
        console.log(
          green(`${sdkJson.name}@${version} deprecated with message ${message}`)
        );
      } catch (e) {
        console.error(
          red(`${sdkJson.name} failed to deprecate version ${version}.`)
        );
        console.error(e);
      }
    }
  }
})();
Example #5
Source File: dependency-version-compare.ts    From eslint-config-kit with MIT License 5 votes vote down vote up
export function equals(version: string, target: string): boolean {
  if (!valid(version)) {
    return false
  }

  return eq(version, target)
}
Example #6
Source File: telemetry.controller.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
private isValidTelemetryVersion(version: string): boolean {
    const parsed = valid(version);
    if (!parsed) {
      return false;
    }
    return gte(parsed, this.MINIMUM_TELEMETRY_VERSION);
  }
Example #7
Source File: MigrationPlan.ts    From elasticsearch-index-migrate with MIT License 5 votes vote down vote up
export function generateState(
    context: MigrationPlanContext,
    resolvedMigration?: ResolvedMigration,
    appliedMigration?: AppliedMigration
): MigrationStateInfo | undefined {
    if (!appliedMigration) {
        if (resolvedMigration?.version) {
            if (
                valid(resolvedMigration?.version) &&
                valid(context.baseline) &&
                lt(resolvedMigration?.version, context.baseline)
            ) {
                return MigrationStateInfo.get(MigrationStates.BELOW_BASELINE);
            }
            if (
                valid(resolvedMigration?.version) &&
                valid(context.lastApplied) &&
                lt(resolvedMigration?.version, context.lastApplied)
            ) {
                return MigrationStateInfo.get(MigrationStates.IGNORED);
            }
        }
        return MigrationStateInfo.get(MigrationStates.PENDING);
    }

    if (
        valid(appliedMigration?.version) &&
        valid(context.baseline) &&
        appliedMigration?.version === context.baseline &&
        appliedMigration?.success
    ) {
        return MigrationStateInfo.get(MigrationStates.BASELINE);
    }

    if (!resolvedMigration) {
        const version = generateVersion(resolvedMigration, appliedMigration) ?? '';
        if (
            !appliedMigration.version ||
            (valid(context.lastResolved) && valid(version) && lt(version, context.lastResolved))
        ) {
            if (appliedMigration?.success) {
                return MigrationStateInfo.get(MigrationStates.MISSING_SUCCESS);
            }
            return MigrationStateInfo.get(MigrationStates.MISSING_FAILED);
        } else {
            if (appliedMigration.success) {
                return MigrationStateInfo.get(MigrationStates.FUTURE_SUCCESS);
            }
            return MigrationStateInfo.get(MigrationStates.FUTURE_FAILED);
        }
    }

    if (!appliedMigration?.success) {
        return MigrationStateInfo.get(MigrationStates.FAILED);
    }

    return MigrationStateInfo.get(MigrationStates.SUCCESS);
}
Example #8
Source File: extensions.local.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
async install(name: string, version: string): Promise<IExtensionInfo> {
        if (!version) {
            throw new InvalidArgumentError('Version must be specified');
        }

        const {extensionsCache, tmp} = this.environment.dirPaths;
        const isFilePath = (await fse.pathExists(version)) && (await fse.stat(version)).isFile();

        // version as a file path or URL.
        if (isFilePath || isValidUrl(version)) {
            let toExtract = version;

            if (isValidUrl(version)) {
                const tmpDownloadPath = path.join(tmp, uuidv4());

                await emitHookEvent(HOOK_EVENTS.RELATE_EXTENSION_DOWNLOAD_START, null);

                toExtract = await download(version, tmpDownloadPath);

                await emitHookEvent(HOOK_EVENTS.RELATE_EXTENSION_DOWNLOAD_STOP, null);
            }

            // extract extension to tmp first
            const tmpExtractPath = path.join(tmp, uuidv4());
            const {
                name: extensionName,
                dist,
                version: extensionVersion,
            } = await extractExtension(toExtract, tmpExtractPath);
            const cacheDir = path.join(extensionsCache, `${extensionName}@${extensionVersion}`);

            // move the extracted dir to cache
            await fse.move(dist, cacheDir, {
                overwrite: true,
            });
            await fse.remove(tmpExtractPath);

            try {
                const discovered = await discoverExtension(cacheDir);

                return this.installRelateExtension(discovered, discovered.dist).finally(() => fse.remove(cacheDir));
            } catch (e) {
                throw new NotFoundError(`Unable to find the requested version: ${version}`);
            }
        }

        const coercedVersion = valid(version);
        if (coercedVersion) {
            const dists = List.from(await discoverExtensionDistributions(extensionsCache));
            const requestedDistribution = await dists
                .find((dist) => dist.name === name && dist.version === coercedVersion)
                .flatMap((requested) => {
                    if (None.isNone(requested)) {
                        try {
                            return downloadExtension(name, coercedVersion, extensionsCache);
                        } catch (e) {
                            throw new NotFoundError(`Unable to find the requested version: ${version} online`);
                        }
                    }

                    return requested;
                });

            return this.installRelateExtension(requestedDistribution, requestedDistribution.dist);
        }

        throw new InvalidArgumentError('Provided version argument is not valid semver, url or path.');
    }
Example #9
Source File: publish-packages.ts    From react-celo with MIT License 4 votes vote down vote up
// This is an async IIFE so that we can use `aync/await`
void (async function () {
  start();

  // `getAnswers` will either prompt the user for a version and whether
  // or not to publish or it will use an existing failedPublish.json file.
  const { packages, version, publish } = await getAnswers();

  if (version && !valid(version) && !VERSIONS.includes(version)) {
    console.error(
      red(
        'Invalid version given. Version must be major, minor, patch, or a semantic version.'
      )
    );
    process.exit(1);
  }

  const shouldPublish =
    publish.toLowerCase() === 'y' || publish.toLowerCase() === 'dry-run';

  if (!shouldPublish && !version) {
    console.error(red('Either a version or --publish must be given'));
    process.exit(1);
  }

  let tag = 'latest';
  const prereleaseArr = prerelease(version);
  if (prereleaseArr) {
    tag = (prereleaseArr[0] + '').trim();

    if (!['alpha', 'beta', 'canary', 'rc'].includes(tag)) {
      const errorPrompt = [
        {
          name: 'confirmTag',
          description: red(
            `Unknown prerelease keyword given, do you really want to publish ${version} with tag ${tag}? Y/N`
          ),
        },
      ];
      const { confirmTag } = await get(errorPrompt);
      if (confirmTag !== 'Y') {
        process.exit(1);
      }
    }
  }

  const packagePaths = findPackagePaths(path.join(__dirname, '..', 'packages'));
  const packageJsons = packagePaths.map(readPackageJson);

  // We need all the names before we go through and update the
  // `package.json` dependencies.
  const packageNames = packageJsons.map(({ name }) => name);

  const currentVersion = removeDevSuffix(packageJsons[0].version);

  let newVersion: string;
  if (!version) {
    newVersion = currentVersion;
  } else {
    newVersion = VERSIONS.includes(version)
      ? incrementVersion(currentVersion, version)
      : version;
  }
  // Here we update the `package.json` objects with updated
  // versions and dependencies.
  packageJsons.forEach((json, index) => {
    json.version = newVersion;

    if (shouldPublish) {
      for (const depName in json.dependencies) {
        if (packageNames.includes(depName)) {
          json.dependencies[depName] = newVersion;
        }
      }
      for (const depName in json.devDependencies) {
        if (packageNames.includes(depName)) {
          json.devDependencies[depName] = newVersion;
        }
      }
    }

    writePackageJson(packagePaths[index], json);
  });

  const otpPrompt = [
    {
      name: 'otp',
      description: green(`Enter 2FA code`),
    },
  ];

  const successfulPackages: string[] = [];
  if (shouldPublish) {
    // Here we build and publish all the packages
    for (let index = 0; index < packagePaths.length; index++) {
      const path = packagePaths[index];
      const packageJson = packageJsons[index];
      if (packages.length && !packages.includes(packageJson.name)) {
        console.log(`Skipping ${packageJson.name}`);
        successfulPackages.push(packageJson.name);
        continue;
      }
      const packageFolderPath = path.replace('package.json', '');
      try {
        console.log(`Building ${packageJson.name}`);
        child_process.execSync('yarn build', {
          cwd: packageFolderPath,
          stdio: 'ignore',
        });

        console.info(
          `Publishing ${packageJson.name}@${packageJson.version} tagged as ${tag}...`
        );
        // Here you enter the 2FA code for npm
        let { otp } = await get<{ otp: string }>(otpPrompt);
        if (!otp) {
          console.error(red('OTP is required. Can be anything for dry run'));
        }

        // Here is the actual publishing
        child_process.execSync(
          `npm publish --access public --otp ${otp} ${
            publish === 'dry-run' ? '--dry-run' : ''
          } --tag ${tag}`,
          { cwd: packageFolderPath, stdio: 'ignore' }
        );
        successfulPackages.push(packageJson.name);
      } catch (e) {
        const errorPrompt = [
          {
            name: 'retry',
            description: red(
              `${packageJson.name} failed to publish. Error message: ${
                (e as Error).message
              } Retry? Y/N`
            ),
          },
        ];
        const { retry } = await get(errorPrompt);
        if (retry === 'Y') {
          index--;
        }
      }
    }
  }

  // This means some packages were not successfully published
  // but some were published so we need to track the failed ones
  // to keep them in sync.
  if (
    successfulPackages.length &&
    successfulPackages.length !== packageNames.length
  ) {
    const failedPackages = packageNames.filter(
      (name) => !successfulPackages.includes(name)
    );
    console.error(
      red(
        `The following packages failed to publish ${failedPackages.join(', ')}.`
      )
    );
    console.error(red('Creating failed packages file.'));
    fs.writeFileSync(
      path.join(__dirname, 'failedPackages.json'),
      JSON.stringify({ packages: failedPackages, version: undefined, publish })
    );
    console.error(red(`Fix failed packages and try again.`));
    process.exit(1);
  }

  const failedJsonPath = path.join(__dirname, 'failedPackages.json');
  if (fs.existsSync(failedJsonPath)) {
    fs.unlinkSync(failedJsonPath);
  }

  const allPackagePaths = findPackagePaths(
    path.join(__dirname, '..', 'packages')
  );

  const newDevVersion = getNewDevVersion(newVersion);

  // Finally we update all the packages across the monorepo
  // to use the most recent packages.
  allPackagePaths.forEach((path) => {
    const json = readPackageJson(path);

    json.version = `${newVersion}-dev`;

    for (const depName in json.dependencies) {
      if (packageNames.includes(depName)) {
        const versionUpdate = json.dependencies[depName].includes('-dev')
          ? `${newDevVersion}-dev`
          : newVersion;
        json.dependencies[depName] = versionUpdate;
      }
    }
    for (const depName in json.devDependencies) {
      if (packageNames.includes(depName)) {
        const versionUpdate = json.devDependencies[depName].includes('-dev')
          ? `${newDevVersion}-dev`
          : newVersion;
        json.devDependencies[depName] = versionUpdate;
      }
    }
    writePackageJson(path, json);
  });
})();
Example #10
Source File: MigrationPlanExecutor.ts    From elasticsearch-index-migrate with MIT License 4 votes vote down vote up
function MigrationPlanExecutor(
    resolvedMigrations: ResolvedMigration[],
    appliedMigrations: MigrateIndex[],
    migrationPlanContext: MigrationPlanContext
): MigrationPlanExecutorRet {
    const migrationPlans: MigrationPlan[] = [];

    const migrationPlanMap = new Map<string, MigrationPlan>();
    const appliedMigrationVersions = appliedMigrations
        .map((value) => value.migrate_version)
        .filter((value) => valid(value))
        .sort((a, b) => compare(a, b));
    const lastApplied = appliedMigrationVersions[appliedMigrationVersions.length - 1];
    const resolvedMigrationVersions = resolvedMigrations
        .map((value) => value.version)
        .filter((value) => valid(value))
        .sort((a, b) => compare(a, b));
    const lastResolved = resolvedMigrationVersions[resolvedMigrationVersions.length - 1];

    const context: MigrationPlanContext = {
        ...migrationPlanContext,
        lastResolved,
        lastApplied
    };

    resolvedMigrations.forEach((value) => {
        const migrationPlan = migrationPlanMap.get(value.version);
        if (migrationPlan) {
            migrationPlanMap.set(
                value.version,
                generateMigrationPlan(context, value, migrationPlan.appliedMigration)
            );
            migrationPlan.resolvedMigration = value;
        } else {
            migrationPlanMap.set(value.version, generateMigrationPlan(context, value));
        }
    });
    appliedMigrations.forEach((value) => {
        const migrationPlan = migrationPlanMap.get(value.migrate_version);
        const appliedMigration = {
            version: value.migrate_version,
            description: value.description,
            type: MigrationTypes[value.script_type as MigrationType],
            script: value.script_name,
            installedOn: new Date(value.installed_on),
            executionTime: value.execution_time,
            success: value.success
        };
        if (migrationPlan) {
            migrationPlanMap.set(
                value.migrate_version,
                generateMigrationPlan(context, migrationPlan.resolvedMigration, appliedMigration)
            );
        } else {
            migrationPlanMap.set(
                value.migrate_version,
                generateMigrationPlan(context, undefined, appliedMigration)
            );
        }
    });

    const keys: string[] = [];
    migrationPlanMap.forEach((value, key) => {
        keys.push(key);
    });
    const sortedKeys = keys.filter((value) => valid(value)).sort((a, b) => compare(a, b));
    if (sortedKeys.length < 1) {
        cli.error('Unknown version migration detected');
    }
    sortedKeys.forEach((version) => {
        const migrationPlan = migrationPlanMap.get(version);
        if (migrationPlan?.resolvedMigration && migrationPlan?.appliedMigration === undefined) {
            migrationPlans.push(
                generateMigrationPlan(
                    migrationPlan.context,
                    migrationPlan.resolvedMigration,
                    migrationPlan.appliedMigration
                )
            );
        } else if (migrationPlan) {
            migrationPlans.push(migrationPlan);
        }
    });

    return {
        all: migrationPlans,
        pending: migrationPlans.filter((value) => value.state?.status === MigrationStates.PENDING)
    };
}