@alextheman/utility 5.13.0 → 5.14.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.
@@ -33,6 +33,10 @@ const DependencyGroup = {
33
33
  DEV_DEPENDENCIES: "devDependencies"
34
34
  };
35
35
  //#endregion
36
+ //#region src/root/constants/VERSION_NUMBER_REGEX.ts
37
+ const VERSION_NUMBER_PATTERN = String.raw`^(?:v)?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$`;
38
+ const VERSION_NUMBER_REGEX = RegExp(`^${VERSION_NUMBER_PATTERN}$`);
39
+ //#endregion
36
40
  //#region src/root/functions/arrayHelpers/fillArray.ts
37
41
  /**
38
42
  * Creates a new array where each element is the result of the provided callback.
@@ -233,53 +237,49 @@ var DataError = class DataError extends CodeError {
233
237
  }
234
238
  };
235
239
  //#endregion
236
- //#region src/root/functions/parsers/zod/_parseZodSchema.ts
237
- function _parseZodSchema(parsedResult, input, onError) {
238
- if (!parsedResult.success) {
239
- if (onError) {
240
- if (onError instanceof Error) throw onError;
241
- else if (typeof onError === "function") {
242
- const evaluatedError = onError(parsedResult.error);
243
- if (evaluatedError instanceof Error) throw evaluatedError;
244
- }
245
- }
246
- const allErrorCodes = {};
247
- for (const issue of parsedResult.error.issues) {
248
- const code = issue.code.toUpperCase();
249
- allErrorCodes[code] = (allErrorCodes[code] ?? 0) + 1;
250
- }
251
- throw new DataError({ input }, Object.entries(allErrorCodes).toSorted(([_, firstCount], [__, secondCount]) => {
252
- return secondCount - firstCount;
253
- }).map(([code, count], _, allErrorCodes) => {
254
- return allErrorCodes.length === 1 && count === 1 ? code : `${code}×${count}`;
255
- }).join(","), `\n\n${zod.default.prettifyError(parsedResult.error)}\n`);
256
- }
257
- return parsedResult.data;
258
- }
259
- //#endregion
260
- //#region src/root/functions/parsers/zod/parseZodSchema.ts
240
+ //#region src/root/functions/parsers/parseIntStrict.ts
261
241
  /**
262
- * An alternative function to zodSchema.parse() that can be used to strictly parse Zod schemas.
263
- *
264
- * NOTE: Use `parseZodSchemaAsync` if your schema includes an asynchronous function.
242
+ * Converts a string to an integer and throws an error if it cannot be converted.
265
243
  *
266
244
  * @category Parsers
267
245
  *
268
- * @template SchemaType - The Zod schema type.
269
- * @template ErrorType - The type of error to throw on invalid data.
270
- *
271
- * @param schema - The Zod schema to use in parsing.
272
- * @param input - The data to parse.
273
- * @param onError - A custom error to throw on invalid data (defaults to `DataError`). May either be the error itself, or a function that returns the error or nothing. If nothing is returned, the default error is thrown instead.
246
+ * @param string - A string to convert into a number.
247
+ * @param radix - A value between 2 and 36 that specifies the base of the number in string. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.
274
248
  *
275
- * @throws {DataErrorCode} If the given data cannot be parsed according to the schema.
249
+ * @throws {DataError} If the provided string cannot safely be converted to an integer.
276
250
  *
277
- * @returns The parsed data from the Zod schema.
251
+ * @returns The integer parsed from the input string.
278
252
  */
279
- function parseZodSchema(schema, input, onError) {
280
- return _parseZodSchema(schema.safeParse(input), input, onError);
253
+ function parseIntStrict(string, radix) {
254
+ const trimmedString = string.trim();
255
+ const maxAllowedAlphabeticalCharacter = radix && radix > 10 && radix <= 36 ? String.fromCharCode(87 + radix - 1) : void 0;
256
+ if (!(radix && radix > 10 && radix <= 36 ? new RegExp(`^[+-]?[0-9a-${maxAllowedAlphabeticalCharacter}]+$`, "i") : /^[+-]?\d+$/).test(trimmedString)) throw new DataError(radix ? {
257
+ string,
258
+ radix
259
+ } : { string }, "INTEGER_PARSING_ERROR", `Only numeric values${radix && radix > 10 && radix <= 36 ? ` or character${radix !== 11 ? "s" : ""} A${radix !== 11 ? `-${maxAllowedAlphabeticalCharacter?.toUpperCase()} ` : " "}` : " "}are allowed.`);
260
+ if (radix && radix < 10 && [...trimmedString.replace(/^[+-]/, "")].some((character) => {
261
+ return parseInt(character) >= radix;
262
+ })) throw new DataError({
263
+ string,
264
+ radix
265
+ }, "INTEGER_PARSING_ERROR", "Value contains one or more digits outside of the range of the given radix.");
266
+ const parseIntResult = parseInt(trimmedString, radix);
267
+ if (isNaN(parseIntResult)) throw new DataError({ string }, "INTEGER_PARSING_ERROR", "Value is not a valid integer.");
268
+ return parseIntResult;
281
269
  }
282
270
  //#endregion
271
+ //#region src/root/functions/parsers/parseVersionType.ts
272
+ /**
273
+ * Represents the three common software version types.
274
+ *
275
+ * @category Types
276
+ */
277
+ const VersionType = {
278
+ MAJOR: "major",
279
+ MINOR: "minor",
280
+ PATCH: "patch"
281
+ };
282
+ //#endregion
283
283
  //#region src/root/functions/taggedTemplate/interpolate.ts
284
284
  /**
285
285
  * Returns the result of interpolating a template string when given the strings and interpolations separately.
@@ -370,6 +370,276 @@ function normaliseIndents(first, ...args) {
370
370
  return reduceLines(interpolate(strings, ...[...args]).split("\n"), options);
371
371
  }
372
372
  //#endregion
373
+ //#region src/root/types/VersionNumber.ts
374
+ /**
375
+ * Represents a software version number, considered to be made up of a major, minor, and patch part.
376
+ *
377
+ * @category Types
378
+ */
379
+ var VersionNumber = class VersionNumber {
380
+ static NON_NEGATIVE_TUPLE_ERROR = "Input array must be a tuple of three non-negative integers.";
381
+ /** The major number. Increments when a feature is removed or changed in a way that is not backwards-compatible with the previous release. */
382
+ major = 0;
383
+ /** The minor number. Increments when a new feature is added/deprecated and is expected to be backwards-compatible with the previous release. */
384
+ minor = 0;
385
+ /** The patch number. Increments when the next release is fixing a bug or doing a small refactor that should not be noticeable in practice. */
386
+ patch = 0;
387
+ /**
388
+ * @param input - The input to create a new instance of `VersionNumber` from.
389
+ */
390
+ constructor(input) {
391
+ if (input instanceof VersionNumber) {
392
+ this.major = input.major;
393
+ this.minor = input.minor;
394
+ this.patch = input.patch;
395
+ } else if (typeof input === "string") {
396
+ if (!VERSION_NUMBER_REGEX.test(input)) throw new DataError({ input }, "INVALID_VERSION", `"${input}" is not a valid version number. Version numbers must be of the format "X.Y.Z" or "vX.Y.Z", where X, Y, and Z are non-negative integers.`);
397
+ const [major, minor, patch] = VersionNumber.formatString(input, { omitPrefix: true }).split(".").map((number) => {
398
+ return parseIntStrict(number);
399
+ });
400
+ this.major = major;
401
+ this.minor = minor;
402
+ this.patch = patch;
403
+ } else if (Array.isArray(input)) {
404
+ if (input.length !== 3) throw new DataError({ input }, "INVALID_LENGTH", VersionNumber.NON_NEGATIVE_TUPLE_ERROR);
405
+ const [major, minor, patch] = input.map((number) => {
406
+ const parsedInteger = parseIntStrict(number?.toString());
407
+ if (parsedInteger < 0) throw new DataError({ input }, "NEGATIVE_INPUTS", VersionNumber.NON_NEGATIVE_TUPLE_ERROR);
408
+ return parsedInteger;
409
+ });
410
+ this.major = major;
411
+ this.minor = minor;
412
+ this.patch = patch;
413
+ } else throw new DataError({ input }, "INVALID_INPUT", normaliseIndents`
414
+ The provided input can not be parsed into a valid version number.
415
+ Expected either a string of format X.Y.Z or vX.Y.Z, a tuple of three numbers, or another \`VersionNumber\` instance.
416
+ `);
417
+ }
418
+ /**
419
+ * Gets the current version type of the current instance of `VersionNumber`.
420
+ *
421
+ * @returns Either `"major"`, `"minor"`, or `"patch"`, depending on the version type.
422
+ */
423
+ get type() {
424
+ if (this.minor === 0 && this.patch === 0) return VersionType.MAJOR;
425
+ if (this.patch === 0) return VersionType.MINOR;
426
+ return VersionType.PATCH;
427
+ }
428
+ static formatString(input, options) {
429
+ if (options?.omitPrefix) return input.startsWith("v") ? input.slice(1) : input;
430
+ return input.startsWith("v") ? input : `v${input}`;
431
+ }
432
+ /**
433
+ * Checks if the provided version numbers have the exact same major, minor, and patch numbers.
434
+ *
435
+ * @param firstVersion - The first version number to compare.
436
+ * @param secondVersion - The second version number to compare.
437
+ *
438
+ * @returns `true` if the provided version numbers have exactly the same major, minor, and patch numbers, and returns `false` otherwise.
439
+ */
440
+ static isEqual(firstVersion, secondVersion) {
441
+ return firstVersion.major === secondVersion.major && firstVersion.minor === secondVersion.minor && firstVersion.patch === secondVersion.patch;
442
+ }
443
+ /**
444
+ * Get a formatted string representation of the current version number
445
+ *
446
+ * @param options - Options to apply to the string formatting.
447
+ *
448
+ * @returns A formatted string representation of the current version number with the options applied.
449
+ */
450
+ format(options) {
451
+ let baseOutput = `${this.major}`;
452
+ if (!options?.omitMinor) {
453
+ baseOutput += `.${this.minor}`;
454
+ if (!options?.omitPatch) baseOutput += `.${this.patch}`;
455
+ }
456
+ return VersionNumber.formatString(baseOutput, { omitPrefix: options?.omitPrefix });
457
+ }
458
+ /**
459
+ * Increments the current version number by the given increment type, returning the result as a new reference in memory.
460
+ *
461
+ * @param incrementType - The type of increment. Can be one of the following:
462
+ * - `"major"`: Change the major version `v1.2.3` → `v2.0.0`
463
+ * - `"minor"`: Change the minor version `v1.2.3` → `v1.3.0`
464
+ * - `"patch"`: Change the patch version `v1.2.3` → `v1.2.4`
465
+ * @param incrementAmount - The amount to increment by (defaults to 1).
466
+ *
467
+ * @returns A new instance of `VersionNumber` with the increment applied.
468
+ */
469
+ increment(incrementType, incrementAmount = 1) {
470
+ const incrementBy = parseIntStrict(String(incrementAmount));
471
+ const calculatedRawVersion = {
472
+ major: [
473
+ this.major + incrementBy,
474
+ 0,
475
+ 0
476
+ ],
477
+ minor: [
478
+ this.major,
479
+ this.minor + incrementBy,
480
+ 0
481
+ ],
482
+ patch: [
483
+ this.major,
484
+ this.minor,
485
+ this.patch + incrementBy
486
+ ]
487
+ }[incrementType];
488
+ try {
489
+ return new VersionNumber(calculatedRawVersion);
490
+ } catch (error) {
491
+ if (DataError.check(error) && error.code === "NEGATIVE_INPUTS") throw new DataError({
492
+ currentVersion: this.toString(),
493
+ calculatedRawVersion: `v${calculatedRawVersion.join(".")}`,
494
+ incrementAmount
495
+ }, "NEGATIVE_VERSION", "Cannot apply this increment amount as it would lead to a negative version number.");
496
+ else throw error;
497
+ }
498
+ }
499
+ /**
500
+ * Ensures that the VersionNumber behaves correctly when attempted to be coerced to a string.
501
+ *
502
+ * @param hint - Not used as of now, but generally used to help with numeric coercion, I think (which we most likely do not need for version numbers).
503
+ *
504
+ * @returns A stringified representation of the current version number, prefixed with `v`.
505
+ */
506
+ [Symbol.toPrimitive](hint) {
507
+ if (hint === "number") throw new DataError({ thisVersion: this.toString() }, "INVALID_COERCION", "VersionNumber cannot be coerced to a number type.");
508
+ return this.toString();
509
+ }
510
+ /**
511
+ * Ensures that the VersionNumber behaves correctly when attempted to be converted to JSON.
512
+ *
513
+ * @returns A stringified representation of the current version number, prefixed with `v`.
514
+ */
515
+ toJSON() {
516
+ return this.toString();
517
+ }
518
+ /**
519
+ * Get a string representation of the current version number.
520
+ *
521
+ * @returns A stringified representation of the current version number with the prefix.
522
+ */
523
+ toString() {
524
+ const rawString = `${this.major}.${this.minor}.${this.patch}`;
525
+ return VersionNumber.formatString(rawString, { omitPrefix: false });
526
+ }
527
+ };
528
+ const zodVersionNumber = zod.default.union([
529
+ zod.default.string(),
530
+ zod.default.tuple([
531
+ zod.default.number(),
532
+ zod.default.number(),
533
+ zod.default.number()
534
+ ]),
535
+ zod.default.instanceof(VersionNumber)
536
+ ]).transform((rawVersionNumber) => {
537
+ return new VersionNumber(rawVersionNumber);
538
+ });
539
+ //#endregion
540
+ //#region src/root/zod/_parseZodSchema.ts
541
+ function _parseZodSchema(parsedResult, input, onError) {
542
+ if (!parsedResult.success) {
543
+ if (onError) {
544
+ if (onError instanceof Error) throw onError;
545
+ else if (typeof onError === "function") {
546
+ const evaluatedError = onError(parsedResult.error);
547
+ if (evaluatedError instanceof Error) throw evaluatedError;
548
+ }
549
+ }
550
+ const allErrorCodes = {};
551
+ for (const issue of parsedResult.error.issues) {
552
+ const code = issue.code.toUpperCase();
553
+ allErrorCodes[code] = (allErrorCodes[code] ?? 0) + 1;
554
+ }
555
+ throw new DataError({ input }, Object.entries(allErrorCodes).toSorted(([_, firstCount], [__, secondCount]) => {
556
+ return secondCount - firstCount;
557
+ }).map(([code, count], _, allErrorCodes) => {
558
+ return allErrorCodes.length === 1 && count === 1 ? code : `${code}×${count}`;
559
+ }).join(","), `\n\n${zod.default.prettifyError(parsedResult.error)}\n`);
560
+ }
561
+ return parsedResult.data;
562
+ }
563
+ //#endregion
564
+ //#region src/root/zod/parseZodSchema.ts
565
+ /**
566
+ * An alternative function to zodSchema.parse() that can be used to strictly parse Zod schemas.
567
+ *
568
+ * NOTE: Use `parseZodSchemaAsync` if your schema includes an asynchronous function.
569
+ *
570
+ * @category Parsers
571
+ *
572
+ * @deprecated Please use `az.with(schema).parse(input)` instead.
573
+ *
574
+ * @template SchemaType - The Zod schema type.
575
+ * @template ErrorType - The type of error to throw on invalid data.
576
+ *
577
+ * @param schema - The Zod schema to use in parsing.
578
+ * @param input - The data to parse.
579
+ * @param onError - A custom error to throw on invalid data (defaults to `DataError`). May either be the error itself, or a function that returns the error or nothing. If nothing is returned, the default error is thrown instead.
580
+ *
581
+ * @throws {DataErrorCode} If the given data cannot be parsed according to the schema.
582
+ *
583
+ * @returns The parsed data from the Zod schema.
584
+ */
585
+ function parseZodSchema(schema, input, onError) {
586
+ return _parseZodSchema(schema.safeParse(input), input, onError);
587
+ }
588
+ //#endregion
589
+ //#region src/root/zod/parseZodSchemaAsync.ts
590
+ /**
591
+ * An alternative function to zodSchema.parseAsync() that can be used to strictly parse asynchronous Zod schemas.
592
+ *
593
+ * @category Parsers
594
+ *
595
+ * @deprecated Please use `az.with(schema).parseAsync(input)` instead.
596
+ *
597
+ * @template SchemaType - The Zod schema type.
598
+ * @template ErrorType - The type of error to throw on invalid data.
599
+ *
600
+ * @param schema - The Zod schema to use in parsing.
601
+ * @param input - The data to parse.
602
+ * @param onError - A custom error to throw on invalid data (defaults to `DataError`). May either be the error itself, or a function that returns the error or nothing. If nothing is returned, the default error is thrown instead.
603
+ *
604
+ * @throws {DataError} If the given data cannot be parsed according to the schema.
605
+ *
606
+ * @returns The parsed data from the Zod schema.
607
+ */
608
+ async function parseZodSchemaAsync(schema, input, onError) {
609
+ return _parseZodSchema(await schema.safeParseAsync(input), input, onError);
610
+ }
611
+ //#endregion
612
+ //#region src/root/zod/zodFieldWrapper.ts
613
+ function zodFieldWrapper(schema) {
614
+ return zod.default.string().trim().transform((value) => {
615
+ return value === "" ? null : value;
616
+ }).pipe(schema);
617
+ }
618
+ //#endregion
619
+ //#region src/root/zod/az.ts
620
+ const az = {
621
+ field: zodFieldWrapper,
622
+ fieldNumber: () => {
623
+ return zod.default.coerce.number();
624
+ },
625
+ versionNumber: () => {
626
+ return zodVersionNumber;
627
+ },
628
+ fieldDate: () => {
629
+ return zod.default.coerce.date();
630
+ },
631
+ with: (schema) => {
632
+ return {
633
+ parse: (input, error) => {
634
+ return parseZodSchema(schema, input, error);
635
+ },
636
+ parseAsync: async (input, error) => {
637
+ return await parseZodSchemaAsync(schema, input, error);
638
+ }
639
+ };
640
+ }
641
+ };
642
+ //#endregion
373
643
  //#region src/internal/getDependenciesFromGroup.ts
374
644
  /**
375
645
  * Get the dependencies from a given dependency group in `package.json`.
@@ -383,8 +653,8 @@ function normaliseIndents(first, ...args) {
383
653
  */
384
654
  function getDependenciesFromGroup(packageInfo, dependencyGroup) {
385
655
  return {
386
- dependencies: parseZodSchema(zod.default.record(zod.default.string(), zod.default.string()), packageInfo.dependencies ?? {}),
387
- devDependencies: parseZodSchema(zod.default.record(zod.default.string(), zod.default.string()), packageInfo.devDependencies ?? {})
656
+ dependencies: az.with(zod.default.record(zod.default.string(), zod.default.string())).parse(packageInfo.dependencies ?? {}),
657
+ devDependencies: az.with(zod.default.record(zod.default.string(), zod.default.string())).parse(packageInfo.devDependencies ?? {})
388
658
  }[dependencyGroup];
389
659
  }
390
660
  //#endregion
@@ -392,7 +662,7 @@ function getDependenciesFromGroup(packageInfo, dependencyGroup) {
392
662
  async function getExpectedTgzName(packagePath, packageManager) {
393
663
  const { stdout: rawPackedTgzData } = await (0, execa.execa)({ cwd: packagePath })`${packageManager} pack --json --dry-run`;
394
664
  const packedTgzData = parseJsonFromStdout(rawPackedTgzData);
395
- const parsedPackedTgzData = parseZodSchema(packageManager === "pnpm" ? zod.default.object({ filename: zod.default.string() }) : zod.default.array(zod.default.object({ filename: zod.default.string() })), packedTgzData, new DataError(packedTgzData, "AMBIGUOUS_EXPECTED_FILE_NAME", "Could not figure out the expected filename."));
665
+ const parsedPackedTgzData = az.with(packageManager === "pnpm" ? zod.default.object({ filename: zod.default.string() }) : zod.default.array(zod.default.object({ filename: zod.default.string() }))).parse(packedTgzData, new DataError(packedTgzData, "AMBIGUOUS_EXPECTED_FILE_NAME", "Could not figure out the expected filename."));
396
666
  const [normalisedTgzMetadata] = Array.isArray(parsedPackedTgzData) ? parsedPackedTgzData : [parsedPackedTgzData];
397
667
  const { filename: expectedTgzFileName } = normalisedTgzMetadata;
398
668
  return expectedTgzFileName;