Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@dynatrace-sdk/units

Package Overview
Dependencies
Maintainers
3
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@dynatrace-sdk/units - npm Package Compare versions

Comparing version 0.10.1 to 0.11.0

types/packages/util/units/src/util-format/timeParser.d.ts

12

CHANGELOG.md

@@ -5,2 +5,14 @@ # Units

## 0.11.0
### Minor Changes
- Add parseTime to the units package.
### Patch Changes
- Make undefined a valid input unit.
- Make number abbreviation respect locale.
- Make core unit cascade.
## 0.10.1

@@ -7,0 +19,0 @@

179

cjs/index.js

@@ -48,2 +48,3 @@ /**

getFormatting: () => getFormatting,
parseTime: () => parseTime,
units: () => units28,

@@ -673,31 +674,26 @@ variantNames: () => variantNames,

var PIXEL_INDICES = [9, 6, 0];
addExistingGroupToCascade("core", [0, -3]);
addExistingGroupToCascade("pixel", PIXEL_INDICES);
// packages/util/units/src/util-format/adjust-maximum-fraction-digits.ts
var ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS = {
minimumFractionDigits: void 0,
maximumFractionDigits: void 0
var ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS_NO_OPTIONS = {
minimumFractionDigits: 0,
maximumFractionDigits: 0
};
function noOptionsSet(options) {
return options?.minimumFractionDigits === void 0 && options?.maximumFractionDigits === void 0;
}
function adjustFractionDigits(input, options) {
let minimumFractionDigits = options?.minimumFractionDigits ?? ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS.minimumFractionDigits;
let maximumFractionDigits = options?.maximumFractionDigits ?? ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS.maximumFractionDigits;
if (minimumFractionDigits === void 0 && maximumFractionDigits === void 0) {
minimumFractionDigits = 0;
maximumFractionDigits = 0;
}
const calcValue = Math.abs(input);
if (calcValue === 0) {
return "0";
}
const minValue = 1 / Math.pow(10, Math.max(...[maximumFractionDigits ?? 0, 0]));
if (calcValue < minValue) {
return input < 0 ? `-${minValue}` : `< ${minValue}`;
}
options = {
...options,
...noOptionsSet(options) ? ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS_NO_OPTIONS : {}
};
let locale = options?.locale;
locale ??= getRegionalLocale();
locale = safeLocale(locale);
const formatter = new Intl.NumberFormat(locale, {
maximumFractionDigits,
minimumFractionDigits
});
const formatter = new Intl.NumberFormat(locale, options);
const minValue = 1 / Math.pow(10, Math.max(options.maximumFractionDigits ?? 0, 0));
if (Math.abs(input) < minValue) {
return `${input <= 0 ? "" : "< "}${formatter.format(Math.sign(input) * minValue)}`;
}
return formatter.format(input);

@@ -786,2 +782,3 @@ }

var DEFAULT_LOCALE = "en-US";
var DEFAULT_UNIT = units2.none;
function formatPack({ group: group2, index, exponent }) {

@@ -824,3 +821,3 @@ if (TO_ONE && exponent === 0)

var defaultOptions = {
input: units2.none,
input: DEFAULT_UNIT,
abbreviate: true

@@ -849,3 +846,9 @@ };

function format(number, options) {
const out = formatRaw(number, options);
if (options && options.input === void 0) {
options.input = DEFAULT_UNIT;
}
const out = formatRaw(
number,
options
);
const result = out.map(({ formattedValue, separator, symbol, mode }) => {

@@ -862,3 +865,9 @@ switch (mode) {

function getFormatting(number, options) {
return formatRaw(number, options).map(({ mode, formattedValue: value, ...rest }) => {
if (options && options.input === void 0) {
options.input = DEFAULT_UNIT;
}
return formatRaw(
number,
options
).map(({ mode, formattedValue: value, ...rest }) => {
return { ...rest, value, symbolPrefix: mode === 0 /* Prefix */ };

@@ -1355,1 +1364,123 @@ });

}
// packages/util/units/src/util-format/timeParser.ts
var import_date_fns = require("date-fns");
var import_date_fns2 = require("date-fns");
var import_date_fns3 = require("date-fns");
var import_date_fns4 = require("date-fns");
var import_date_fns5 = require("date-fns");
var import_date_fns6 = require("date-fns");
var import_date_fns7 = require("date-fns");
var import_date_fns8 = require("date-fns");
var import_date_fns9 = require("date-fns");
var import_date_fns10 = require("date-fns");
var TIME_INPUT_FORMATS = [
"yyyy-MM-dd",
"yyyy-MM-dd H:mm",
"yyyy-MM-dd H:mm:ss",
"H:mm",
"H:mm:ss"
];
var UTC_ISO_TIME_EXPRESSION = /(?<iso>^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d{1,3})(?<extended_precision>\d*)(?<timezone>Z)$/;
var TIMEFRAME_EXPRESSION = /^(?:now)?([+-]?\d+)(\w+)$/;
var parseTimeExpression = (candidate) => {
const [expression, offset, unit2] = candidate.match(TIMEFRAME_EXPRESSION) ?? [];
if (expression) {
return { offset: parseInt(offset), unit: unit2 };
}
};
var convertExpressionToDate = ({ offset, unit: unit2 }, relativeDate) => {
const now = new Date(relativeDate);
switch (unit2) {
case "s":
return (0, import_date_fns.addSeconds)(now, offset);
case "m":
return (0, import_date_fns4.addMinutes)(now, offset);
case "h":
return (0, import_date_fns3.addHours)(now, offset);
case "d":
return (0, import_date_fns2.addDays)(now, offset);
case "w":
return (0, import_date_fns6.addWeeks)(now, offset);
case "M":
return (0, import_date_fns5.addMonths)(now, offset);
case "y":
return (0, import_date_fns7.addYears)(now, offset);
}
return null;
};
var parseDatetimeInput = (candidate) => {
const referenceDate = (0, import_date_fns10.startOfToday)();
for (const format2 of TIME_INPUT_FORMATS) {
const date = (0, import_date_fns9.parse)(candidate, format2, referenceDate);
if ((0, import_date_fns8.isValid)(date)) {
return date;
}
}
return null;
};
var parseISOWithExtendedPrecision = (candidate) => {
const match = candidate.match(UTC_ISO_TIME_EXPRESSION);
if (!match?.groups) {
return null;
}
const iso = match.groups["iso"];
const extended_precision = match.groups["extended_precision"] ?? "";
const timezone = match.groups["timezone"];
return {
type: "iso8601",
normalized: `${iso}${extended_precision}${timezone}`,
date: new Date(candidate)
};
};
var parseTime = (candidate, relativeDate = Date.now()) => {
if (!candidate) {
return null;
}
const normalized = candidate.trim();
if (normalized === "now") {
return {
type: "expression",
normalized,
date: new Date(relativeDate)
};
}
const timeDetails = parseTimeExpression(normalized);
if (timeDetails) {
const date2 = convertExpressionToDate(timeDetails, relativeDate);
const { offset, unit: unit2 } = { ...timeDetails };
return date2 ? {
type: "expression",
normalized: `now${offset < 0 ? offset : `+${offset}`}${unit2}`,
date: date2
} : null;
}
const parsedISODateDetails = parseISOWithExtendedPrecision(normalized);
if (parsedISODateDetails) {
return parsedISODateDetails;
}
const date = parseDatetimeInput(normalized);
if (date) {
return {
type: "iso8601",
normalized: date.toISOString(),
date
};
}
return null;
};
/**
* @license
* Copyright 2023 Dynatrace LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

48

docs/DOCS.md

@@ -15,3 +15,3 @@ # Units

<div class="col" style={{textAlign: 'right'}}>
<a href="https://www.npmjs.com/package/@dynatrace-sdk/units/v/0.10.1">v0.10.1</a>
<a href="https://www.npmjs.com/package/@dynatrace-sdk/units/v/0.11.0">v0.11.0</a>
</div>

@@ -97,3 +97,3 @@ </div>

| minimumFractionDigits | <a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a> | <p>The amount of minimumFractionDigits points. See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumfractiondigits">MDN</a>.</p> |
| output | ToUnit | <p>If not specified, the conversion is disabled (e.g. <code>format(1500), output: 1.5K</code>).</p> |
| output | OutputUnit&lt;UndefinedCoalescing&lt;FromUnit &#124; &gt; &#124; ToUnit&gt; | <p>If not specified, the conversion is disabled (e.g. <code>format(1500), output: 1.5K</code>).</p> |
| suffix | <a href="https://developer.mozilla.org/en-US/docs/Glossary/String">string</a> | A custom suffix that overwrites the unit symbol. |

@@ -236,6 +236,6 @@

| Name | Type | Description |
| --------------------------- | -------------------------------------------------------------------------------------------------- | ----------------------------------- |
| number<sup>\*required</sup> | <a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a> | The number that will get formatted. |
| options | <a href="#formatoptions">FormatOptions</a>&lt;Units &#124; ToUnit&lt;Units &#124; FromUnit&gt;&gt; | Formatting options. |
| Name | Type | Description |
| --------------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| number<sup>\*required</sup> | <a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a> | The number that will get formatted. |
| options | <a href="#formatoptions">FormatOptions</a>&lt;UndefinedCoalescing&lt;FromUnit &#124; &gt; &#124; ToUnit&gt; | Formatting options. |

@@ -296,3 +296,3 @@ #### Returns

<div class="padding-bottom--md">
<strong>getFormatting(number,options?): Array&lt;Object&gt;</strong>
<strong>getFormatting(number,options?): Formatting</strong>

@@ -307,6 +307,6 @@ <div class="padding-left--md">

| Name | Type | Description |
| --------------------------- | -------------------------------------------------------------------------------------------------- | ----------------------------------- |
| number<sup>\*required</sup> | <a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a> | The number that will get formatted. |
| options | <a href="#formatoptions">FormatOptions</a>&lt;Units &#124; ToUnit&lt;Units &#124; FromUnit&gt;&gt; | Formatting options. |
| Name | Type | Description |
| --------------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| number<sup>\*required</sup> | <a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a> | The number that will get formatted. |
| options | <a href="#formatoptions">FormatOptions</a>&lt;UndefinedCoalescing&lt;FromUnit &#124; &gt; &#124; ToUnit&gt; | Formatting options. |

@@ -319,2 +319,28 @@ #### Returns

### parseTime
<div class="padding-bottom--md">
<strong>parseTime(candidate?,relativeDate): null &#124; TimeDetails</strong>
<div class="padding-left--md">
You can use the `parseTime` utility function to convert a string into
`TimeDetails`, giving you a normalized version of the input string (trimmed
string), a `Date` object created from the given input, and the type of input.
The type can be either an `expression` or `iso8601` string. If it is not
possible to convert the input, the function will return `null`.
</div>
#### Parameters
| Name | Type |
| --------------------------------- | ----------------------------------------------------------------------------------------- |
| candidate | null &#124; <a href="https://developer.mozilla.org/en-US/docs/Glossary/String">string</a> |
| relativeDate<sup>\*required</sup> | <a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a> |
<!-- no returns -->
</div>
### variantNames

@@ -321,0 +347,0 @@

@@ -635,31 +635,26 @@ /**

var PIXEL_INDICES = [9, 6, 0];
addExistingGroupToCascade("core", [0, -3]);
addExistingGroupToCascade("pixel", PIXEL_INDICES);
// packages/util/units/src/util-format/adjust-maximum-fraction-digits.ts
var ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS = {
minimumFractionDigits: void 0,
maximumFractionDigits: void 0
var ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS_NO_OPTIONS = {
minimumFractionDigits: 0,
maximumFractionDigits: 0
};
function noOptionsSet(options) {
return options?.minimumFractionDigits === void 0 && options?.maximumFractionDigits === void 0;
}
function adjustFractionDigits(input, options) {
let minimumFractionDigits = options?.minimumFractionDigits ?? ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS.minimumFractionDigits;
let maximumFractionDigits = options?.maximumFractionDigits ?? ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS.maximumFractionDigits;
if (minimumFractionDigits === void 0 && maximumFractionDigits === void 0) {
minimumFractionDigits = 0;
maximumFractionDigits = 0;
}
const calcValue = Math.abs(input);
if (calcValue === 0) {
return "0";
}
const minValue = 1 / Math.pow(10, Math.max(...[maximumFractionDigits ?? 0, 0]));
if (calcValue < minValue) {
return input < 0 ? `-${minValue}` : `< ${minValue}`;
}
options = {
...options,
...noOptionsSet(options) ? ADJUST_FRACTION_DIGITS_DEFAULT_OPTIONS_NO_OPTIONS : {}
};
let locale = options?.locale;
locale ??= getRegionalLocale();
locale = safeLocale(locale);
const formatter = new Intl.NumberFormat(locale, {
maximumFractionDigits,
minimumFractionDigits
});
const formatter = new Intl.NumberFormat(locale, options);
const minValue = 1 / Math.pow(10, Math.max(options.maximumFractionDigits ?? 0, 0));
if (Math.abs(input) < minValue) {
return `${input <= 0 ? "" : "< "}${formatter.format(Math.sign(input) * minValue)}`;
}
return formatter.format(input);

@@ -748,2 +743,3 @@ }

var DEFAULT_LOCALE = "en-US";
var DEFAULT_UNIT = units2.none;
function formatPack({ group: group2, index, exponent }) {

@@ -786,3 +782,3 @@ if (TO_ONE && exponent === 0)

var defaultOptions = {
input: units2.none,
input: DEFAULT_UNIT,
abbreviate: true

@@ -811,3 +807,9 @@ };

function format(number, options) {
const out = formatRaw(number, options);
if (options && options.input === void 0) {
options.input = DEFAULT_UNIT;
}
const out = formatRaw(
number,
options
);
const result = out.map(({ formattedValue, separator, symbol, mode }) => {

@@ -824,3 +826,9 @@ switch (mode) {

function getFormatting(number, options) {
return formatRaw(number, options).map(({ mode, formattedValue: value, ...rest }) => {
if (options && options.input === void 0) {
options.input = DEFAULT_UNIT;
}
return formatRaw(
number,
options
).map(({ mode, formattedValue: value, ...rest }) => {
return { ...rest, value, symbolPrefix: mode === 0 /* Prefix */ };

@@ -1317,2 +1325,109 @@ });

}
// packages/util/units/src/util-format/timeParser.ts
import { addSeconds } from "date-fns";
import { addDays } from "date-fns";
import { addHours } from "date-fns";
import { addMinutes } from "date-fns";
import { addMonths } from "date-fns";
import { addWeeks } from "date-fns";
import { addYears } from "date-fns";
import { isValid } from "date-fns";
import { parse } from "date-fns";
import { startOfToday } from "date-fns";
var TIME_INPUT_FORMATS = [
"yyyy-MM-dd",
"yyyy-MM-dd H:mm",
"yyyy-MM-dd H:mm:ss",
"H:mm",
"H:mm:ss"
];
var UTC_ISO_TIME_EXPRESSION = /(?<iso>^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d{1,3})(?<extended_precision>\d*)(?<timezone>Z)$/;
var TIMEFRAME_EXPRESSION = /^(?:now)?([+-]?\d+)(\w+)$/;
var parseTimeExpression = (candidate) => {
const [expression, offset, unit2] = candidate.match(TIMEFRAME_EXPRESSION) ?? [];
if (expression) {
return { offset: parseInt(offset), unit: unit2 };
}
};
var convertExpressionToDate = ({ offset, unit: unit2 }, relativeDate) => {
const now = new Date(relativeDate);
switch (unit2) {
case "s":
return addSeconds(now, offset);
case "m":
return addMinutes(now, offset);
case "h":
return addHours(now, offset);
case "d":
return addDays(now, offset);
case "w":
return addWeeks(now, offset);
case "M":
return addMonths(now, offset);
case "y":
return addYears(now, offset);
}
return null;
};
var parseDatetimeInput = (candidate) => {
const referenceDate = startOfToday();
for (const format2 of TIME_INPUT_FORMATS) {
const date = parse(candidate, format2, referenceDate);
if (isValid(date)) {
return date;
}
}
return null;
};
var parseISOWithExtendedPrecision = (candidate) => {
const match = candidate.match(UTC_ISO_TIME_EXPRESSION);
if (!match?.groups) {
return null;
}
const iso = match.groups["iso"];
const extended_precision = match.groups["extended_precision"] ?? "";
const timezone = match.groups["timezone"];
return {
type: "iso8601",
normalized: `${iso}${extended_precision}${timezone}`,
date: new Date(candidate)
};
};
var parseTime = (candidate, relativeDate = Date.now()) => {
if (!candidate) {
return null;
}
const normalized = candidate.trim();
if (normalized === "now") {
return {
type: "expression",
normalized,
date: new Date(relativeDate)
};
}
const timeDetails = parseTimeExpression(normalized);
if (timeDetails) {
const date2 = convertExpressionToDate(timeDetails, relativeDate);
const { offset, unit: unit2 } = { ...timeDetails };
return date2 ? {
type: "expression",
normalized: `now${offset < 0 ? offset : `+${offset}`}${unit2}`,
date: date2
} : null;
}
const parsedISODateDetails = parseISOWithExtendedPrecision(normalized);
if (parsedISODateDetails) {
return parsedISODateDetails;
}
const date = parseDatetimeInput(normalized);
if (date) {
return {
type: "iso8601",
normalized: date.toISOString(),
date
};
}
return null;
};
export {

@@ -1329,2 +1444,3 @@ ExponentialDecimalLevels,

getFormatting,
parseTime,
units28 as units,

@@ -1334,1 +1450,16 @@ variantNames,

};
/**
* @license
* Copyright 2023 Dynatrace LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"name": "@dynatrace-sdk/units",
"version": "0.10.1",
"version": "0.11.0",
"license": "Apache-2.0",

@@ -16,2 +16,6 @@ "description": "Tools for converting and formatting the units and numerical values.",

],
"dependencies": {
"date-fns": "^2.30.0",
"timezone-mock": "^1.3.6"
},
"main": "./cjs/index.js",

@@ -18,0 +22,0 @@ "module": "./esm/index.js",

@@ -8,1 +8,2 @@ export { getFormatting, format, formatDate, formatUnit, FormatDateOptions, FormatOptions, } from './util-format/format';

export { ConvertibleUnit as ConvertibleUnit, FormattableUnit as FormattableUnit, Unit, } from './util-convert/types';
export { parseTime } from './util-format/timeParser';

@@ -69,3 +69,3 @@ import { properties } from './properties';

export declare type isConvertible<T extends Unit | string> = T extends ConvertibleUnit ? true : false;
export declare type ToUnit<T extends Unit | string, U extends ConvertibleUnit> = T extends ConvertibleUnit ? ConvertibleTarget<T, U> : never;
export declare type OutputUnit<T extends Unit | string, U extends ConvertibleUnit> = T extends ConvertibleUnit ? ConvertibleTarget<T, U> : never;
export declare type ToCascade<T extends Unit | string> = isConvertible<T> extends true ? number : never;

@@ -234,2 +234,3 @@ export declare type ValueUnit = {

};
export declare type UndefinedCoalescing<T, U> = T extends undefined ? U : T;
export {};

@@ -1,3 +0,15 @@

import type { Unit, FormattableUnit, ConvertibleUnit, ToUnit, ConvertiblePack } from '../util-convert/types';
import type { Unit, FormattableUnit, ConvertibleUnit, OutputUnit, ConvertiblePack, UndefinedCoalescing } from '../util-convert/types';
declare type Formatting = {
separator: string;
symbol: string;
symbolPrefix: boolean;
value: string;
}[];
export declare const DEFAULT_LOCALE = "en-US";
declare const DEFAULT_UNIT: [Readonly<{
group: "none";
index: 0;
exponent: 1;
}>];
declare type DEFAULT_UNIT_TYPE = typeof DEFAULT_UNIT;
/**

@@ -16,3 +28,3 @@ * Takes a single unit building block and formats it.

export declare function formatUnit(unit: FormattableUnit): string;
export interface FormatOptions<FromUnit extends Unit, ToUnit extends ConvertibleUnit> {
export interface FormatOptions<FromUnit extends Unit | undefined, ToUnit extends ConvertibleUnit> {
/**

@@ -33,3 +45,3 @@ * Will search for the biggest unit within its group and cascade it down the the specified dept.

*/
output?: ToUnit;
output?: OutputUnit<UndefinedCoalescing<FromUnit, DEFAULT_UNIT_TYPE>, ToUnit>;
/** A custom suffix that overwrites the unit symbol. */

@@ -64,3 +76,3 @@ suffix?: string;

*/
export declare function format<Units extends Unit, FromUnit extends ConvertibleUnit>(number: number, options?: FormatOptions<Units, ToUnit<Units, FromUnit>>): string;
export declare function format<FromUnit extends Unit | undefined, ToUnit extends ConvertibleUnit>(number: number, options?: FormatOptions<UndefinedCoalescing<FromUnit, DEFAULT_UNIT_TYPE>, ToUnit>): string;
/**

@@ -72,8 +84,3 @@ * Converts and formats the provided number, but returns the formatting as parts.

*/
export declare function getFormatting<Units extends Unit, FromUnit extends ConvertibleUnit>(number: number, options?: FormatOptions<Units, ToUnit<Units, FromUnit>>): {
value: string;
symbolPrefix: boolean;
symbol: string;
separator: string;
}[];
export declare function getFormatting<FromUnit extends Unit | undefined, ToUnit extends ConvertibleUnit>(number: number, options?: FormatOptions<UndefinedCoalescing<FromUnit, DEFAULT_UNIT_TYPE>, ToUnit>): Formatting;
/**

@@ -100,1 +107,2 @@ * Interface that extends Intl.DateTimeFormatOptions to pass an optional property to overwrite the default locale.

export declare function removeLocaleLVariant(locale: string): string;
export {};
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc