Socket
Socket
Sign inDemoInstall

@handy-common-utils/misc-utils

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@handy-common-utils/misc-utils - npm Package Compare versions

Comparing version 1.1.0 to 1.2.0

dist/http-status.d.ts

1

dist/index.d.ts

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

export * from './mask';
export * from './http-status';
//# sourceMappingURL=index.d.ts.map

@@ -80,1 +80,2 @@ "use strict";

tslib_1.__exportStar(require("./mask"), exports);
tslib_1.__exportStar(require("./http-status"), exports);

2

dist/line-logger.d.ts

@@ -96,3 +96,3 @@ interface MedikooLogFunction {

*/
export declare type ConsoleLineLogger = ReturnType<typeof LineLogger.console>;
export type ConsoleLineLogger = ReturnType<typeof LineLogger.console>;
/**

@@ -99,0 +99,0 @@ * Build an encapsulation of console output functions with console.log/info/warn/error.

@@ -39,27 +39,2 @@ "use strict";

/**
* Constructor
* @param debugFunction function for outputting debug information
* @param infoFunction function for outputting info information
* @param warnFunction function for outputting warn information
* @param errorFunction function for outputting error information
* @param isDebug is debug output enabled or not, it could be overriden by isQuiet
* @param isQuiet is quiet mode enabled or not. When quiet mode is enabled, both debug and info output would be discarded.
*/
constructor(debugFunction, infoFunction, warnFunction, errorFunction, isDebug = false, isQuiet = false) {
this.isDebug = isDebug;
this.isQuiet = isQuiet;
this.info = LineLogger.NO_OP_FUNC;
this.debug = LineLogger.NO_OP_FUNC;
this.warn = LineLogger.NO_OP_FUNC;
this.error = LineLogger.NO_OP_FUNC;
if (isDebug === true && isQuiet !== true) {
this.debug = debugFunction;
}
if (isQuiet !== true) {
this.info = infoFunction;
}
this.warn = warnFunction;
this.error = errorFunction;
}
/**
* Build an instance with console.log/info/warn/error.

@@ -139,2 +114,27 @@ * @param flags The flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled.

}
/**
* Constructor
* @param debugFunction function for outputting debug information
* @param infoFunction function for outputting info information
* @param warnFunction function for outputting warn information
* @param errorFunction function for outputting error information
* @param isDebug is debug output enabled or not, it could be overriden by isQuiet
* @param isQuiet is quiet mode enabled or not. When quiet mode is enabled, both debug and info output would be discarded.
*/
constructor(debugFunction, infoFunction, warnFunction, errorFunction, isDebug = false, isQuiet = false) {
this.isDebug = isDebug;
this.isQuiet = isQuiet;
this.info = LineLogger.NO_OP_FUNC;
this.debug = LineLogger.NO_OP_FUNC;
this.warn = LineLogger.NO_OP_FUNC;
this.error = LineLogger.NO_OP_FUNC;
if (isDebug === true && isQuiet !== true) {
this.debug = debugFunction;
}
if (isQuiet !== true) {
this.info = infoFunction;
}
this.warn = warnFunction;
this.error = errorFunction;
}
}

@@ -141,0 +141,0 @@ exports.LineLogger = LineLogger;

@@ -58,3 +58,3 @@ "use strict";

const segments = email.split('@');
if (segments.length === 2 && segments[0].length >= 3) {
if (segments.length === 2 && segments[0].length > 0) {
const parts = segments[0].split('.');

@@ -61,0 +61,0 @@ segments[0] = parts.map(s => mask(s, 1)).join('.');

@@ -1,6 +0,6 @@

declare type Parent = Record<string | number | symbol, unknown> | Array<unknown>;
type Parent = Record<string | number | symbol, unknown> | Array<unknown>;
/**
* The original replacer expected by JSON.stringify(...)
*/
declare type JsonStringifyReplacer = (this: any, key: string, value: any) => any;
type JsonStringifyReplacer = (this: any, key: string, value: any) => any;
/**

@@ -18,3 +18,3 @@ * The replacer that can potentially utilise the full path of the property in the object.

*/
export declare type PathAwareReplacer = (key: string, value: any, path: string, parent: Parent, pathArray: Array<string>, ancestors: Array<Parent>) => any;
export type PathAwareReplacer = (key: string, value: any, path: string, parent: Parent, pathArray: Array<string>, ancestors: Array<Parent>) => any;
/**

@@ -21,0 +21,0 @@ * Build a replacer function that can be passed to JSON.stringify(...).

{
"name": "@handy-common-utils/misc-utils",
"version": "1.1.0",
"version": "1.2.0",
"description": "Miscellaneous utilities",

@@ -12,3 +12,2 @@ "scripts": {

"files": [
"package.json",
"dist"

@@ -19,11 +18,8 @@ ],

"devDependencies": {
"@handy-common-utils/dev-dependencies": "^1.1.2",
"@handy-common-utils/dev-dependencies-mocha": "^1.3.0",
"@types/log": "^6.3.0",
"@types/node": "^16.11.12",
"@types/sinon": "^10.0.11",
"@types/sinon-chai": "^3.2.8",
"log": "^6.3.1",
"safe-stable-stringify": "^2.4.3",
"sinon": "^14.0.0",
"sinon-chai": "^3.7.0"
"semantic-release": "^21.0.3"
},

@@ -48,5 +44,5 @@ "publishConfig": {

"volta": {
"node": "16.18.0",
"npm": "8.19.2"
"node": "18.16.0",
"npm": "9.5.1"
}
}

@@ -36,2 +36,104 @@ # @handy-common-utils/misc-utils

```typescript
import { mask, maskAll, maskEmail, maskFullName, pathBasedReplacer } from '@handy-common-utils/misc-utils';
const masked = JSON.stringify(obj, pathBasedReplacer([
[/.*\.x-api-key$/, maskAll],
[/.*customer\.name$/, maskFullName],
[/.*customer\..*[eE]mail$/, maskEmail],
[/.*\.zip$/, (value: string) => value.slice(0, 3) + 'XX'],
[/.*\.cc$/, () => undefined],
[/.*\.ssn$/, mask],
]));
```
## Masking
In software development, it's often necessary to hide sensitive information
to protect user privacy or comply with regulations.
Masking is a common technique used to replace part of a sensitive value with a different,
non-sensitive value.
For example, you might mask credit card numbers, passwords, or email addresses.
The `mask(input, keepLeft = 1, keepRight = 0, minLength = 3, maskLengthOrMaskString = null, maskPattern = '*')` function
can be used to mask the content of a string, replacing a part of the input string with a mask string.
It takes several optional parameters, including the number of characters to keep on the left and right sides of the string,
a minimum length for the input string to have unmask characters kept, and the mask pattern to use.
The `maskEmail(input)` and `maskFullName(input)` functions are specific variations of the mask function
that target email addresses and full names, respectively.
The `maskAll(input)` function masks all characters.
```typescript
expect(mask(undefined)).to.be.undefined;
expect(mask(null)).to.be.null;
expect(mask('')).to.equal('');
expect(mask('abcde')).to.equal('a****');
expect(mask('abc')).to.equal('a**');
expect(mask('ab')).to.equal('**');
expect(maskEmail('james.hu@address.com')).to.equal('j****.**@address.com');
expect(maskEmail('her@here.com')).to.equal('h**@here.com');
expect(maskEmail('me@here.com')).to.equal('**@here.com');
expect(maskEmail('my.new.email.address@example.com')).to.equal('**.n**.e****.a******@example.com');
expect(maskFullName('James Hu')).to.equal('J**** **');
expect(maskFullName('John Smith')).to.equal('J*** S****');
expect(maskFullName('Mike')).to.equal('M***');
expect(maskFullName('Mia')).to.equal('M**');
expect(maskFullName('Me')).to.equal('**');
expect(maskFullName('John von Neumann')).to.equal('J*** v** N******');
expect(maskFullName('Two Spaces')).to.equal('T** S*****');
expect(maskFullName('张三丰')).to.equal('张**');
expect(maskFullName('张三')).to.equal('**');
```
## Replacers for JSON.stringify(input, replacer, space)
The `pathAwareReplacer(replacer, options)` function allows you to build a replacer function that can be passed to `JSON.stringify(input, replacer, space)`.
Besides the key, value, and owning object, it also exposes more information to your callback function,
such like the full property path as both a dot (`.`) separated string and as an array, and an array of ancestor objects.
This can be useful when you need to replace specific values in an object, but you also want to know where those values were located in the object.
`pathBasedReplacer` is a function that takes an array of path-based masking rules and returns a function
that can be used as the second parameter in the `JSON.stringify` function.
This function allows you to mask sensitive information during `JSON.stringify` in a very flexible way.
Each element in the rules array contains two parts:
a regular expression that matches the full paths to the values you want to mask or replace,
and a masking or replacing function that takes the original value as input and returns the masked or replaced value.
For example, you could use `pathBasedReplacer` to replace all credit card numbers in an object with masked versions of the numbers:
```typescript
const maskCreditCard = (value: any) => "****-****-****-" + value.slice(-4);
const replacer = pathBasedReplacer([
[/.*billing\.cc$/, maskCreditCard]
]);
const json = JSON.stringify({
to: 'auditor@example.com',
cc: 'auditing-trail@example.com',
year: 2023,
month: 2,
orders: [
{
id: 123,
billing: {
address: '19 High Street',
cc: '1234-5678-2222-3333',
},
},
{
id: 124,
billing: {
address: '88 Main Street',
cc: '3435-8933-0009-2241',
},
},
],
}, replacer, 2);
```
# API

@@ -46,2 +148,3 @@

- [http-status](#moduleshttp_statusmd)
- [index](#modulesindexmd)

@@ -71,6 +174,5 @@ - [line-logger](#modulesline_loggermd)

**`example`**
```javascript
**`Example`**
```ts
// Just a wrapper of console.log/info/warn/error

@@ -90,4 +192,4 @@ const consoleLogger = LineLogger.console();

this.output.warn('Configuration file not found, default configuration would be used.'); // it would be printed out in yellow
```
```
#### Type parameters

@@ -134,9 +236,9 @@

| --- | --- |
| • **debug**: `DEBUG_FUNC` | |
| • **error**: `ERROR_FUNC` | |
| • **info**: `INFO_FUNC` | |
| • **isDebug**: `boolean` = `false` | |
| • **isQuiet**: `boolean` = `false` | |
| • **warn**: `WARN_FUNC` | |
| ▪ `Static` `Protected` **NO\_OP\_FUNC**: () => `void` | **Type declaration:**<br>▸ (): `void`<br><br>**Returns:**<br>`void` |
| **debug**: `DEBUG_FUNC` | |
| **error**: `ERROR_FUNC` | |
| **info**: `INFO_FUNC` | |
| **isDebug**: `boolean` = `false` | is debug output enabled or not, it could be overriden by isQuiet |
| **isQuiet**: `boolean` = `false` | is quiet mode enabled or not. When quiet mode is enabled, both debug and info output would be discarded. |
| **warn**: `WARN_FUNC` | |
| `Static` `Protected` **NO\_OP\_FUNC**: () => `void` | |

@@ -229,5 +331,240 @@

## Enums
<a name="enumshttp_statushttpstatuscodemd"></a>
### Enumeration: HttpStatusCode
[http-status](#moduleshttp_statusmd).HttpStatusCode
Some (not all) well known HTTP status codes
#### Enumeration Members
##### ACCEPTED202
• **ACCEPTED202** = ``202``
The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.
___
##### BAD\_GATEWAY502
• **BAD\_GATEWAY502** = ``502``
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
___
##### BAD\_REQUEST400
• **BAD\_REQUEST400** = ``400``
This response means that server could not understand the request due to invalid syntax.
___
##### CONFLICT409
• **CONFLICT409** = ``409``
This response is sent when a request conflicts with the current state of the server.
___
##### CREATED201
• **CREATED201** = ``201``
The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.
___
##### FORBIDDEN403
• **FORBIDDEN403** = ``403``
The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.
___
##### GATEWAY\_TIMEOUT504
• **GATEWAY\_TIMEOUT504** = ``504``
This error response is given when the server is acting as a gateway and cannot get a response in time.
___
##### INTERNAL\_SERVER\_ERROR500
• **INTERNAL\_SERVER\_ERROR500** = ``500``
The server encountered an unexpected condition that prevented it from fulfilling the request.
___
##### METHOD\_NOT\_ALLOWED405
• **METHOD\_NOT\_ALLOWED405** = ``405``
The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.
___
##### MOVED\_PERMANENTLY301
• **MOVED\_PERMANENTLY301** = ``301``
This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.
___
##### MOVED\_TEMPORARILY302
• **MOVED\_TEMPORARILY302** = ``302``
This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
___
##### NOT\_FOUND404
• **NOT\_FOUND404** = ``404``
The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.
___
##### NOT\_IMPLEMENTED501
• **NOT\_IMPLEMENTED501** = ``501``
The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
___
##### NO\_CONTENT204
• **NO\_CONTENT204** = ``204``
There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.
___
##### OK200
• **OK200** = ``200``
The request has succeeded. The meaning of a success varies depending on the HTTP method:
GET: The resource has been fetched and is transmitted in the message body.
HEAD: The entity headers are in the message body.
POST: The resource describing the result of the action is transmitted in the message body.
TRACE: The message body contains the request message as received by the server
___
##### PERMANENT\_REDIRECT308
• **PERMANENT\_REDIRECT308** = ``308``
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
___
##### REQUEST\_TIMEOUT408
• **REQUEST\_TIMEOUT408** = ``408``
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
___
##### SEE\_OTHER303
• **SEE\_OTHER303** = ``303``
Server sent this response to directing client to get requested resource to another URI with an GET request.
___
##### SERVICE\_UNAVAILABLE503
• **SERVICE\_UNAVAILABLE503** = ``503``
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
___
##### TEMPORARY\_REDIRECT307
• **TEMPORARY\_REDIRECT307** = ``307``
Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
___
##### TOO\_MANY\_REQUESTS429
• **TOO\_MANY\_REQUESTS429** = ``429``
The user has sent too many requests in a given amount of time ("rate limiting").
___
##### UNAUTHORIZED401
• **UNAUTHORIZED401** = ``401``
Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
## Modules
<a name="moduleshttp_statusmd"></a>
### Module: http-status
#### Enumerations
- [HttpStatusCode](#enumshttp_statushttpstatuscodemd)
#### Variables
##### HttpStatusMessage
• `Const` **HttpStatusMessage**: `Object`
Some (not all) HTTP status messages matching their codes
###### Type declaration
| Name | Type |
| :------ | :------ |
| `200` | `string` |
| `201` | `string` |
| `202` | `string` |
| `204` | `string` |
| `301` | `string` |
| `302` | `string` |
| `303` | `string` |
| `307` | `string` |
| `308` | `string` |
| `400` | `string` |
| `401` | `string` |
| `403` | `string` |
| `404` | `string` |
| `405` | `string` |
| `408` | `string` |
| `409` | `string` |
| `429` | `string` |
| `500` | `string` |
| `501` | `string` |
| `502` | `string` |
| `503` | `string` |
| `504` | `string` |
<a name="modulesindexmd"></a>

@@ -245,2 +582,14 @@

##### HttpStatusCode
Re-exports [HttpStatusCode](#enumshttp_statushttpstatuscodemd)
___
##### HttpStatusMessage
Re-exports [HttpStatusMessage](http_status.md#httpstatusmessage)
___
##### LineLogger

@@ -452,3 +801,3 @@

#### Type aliases
#### Type Aliases

@@ -569,7 +918,7 @@ ##### ConsoleLineLogger

| `input` | `T` | `undefined` | The input which could also be null or undefined |
| `keepLeft` | `number` | `1` | Number of characters on the left to be kept in the output without masking. Default value is 1. |
| `keepRight` | `number` | `0` | Number of characters on the right to be kept in the output without masking. Default value is 0. |
| `minLength` | `number` | `3` | Minimal length of the string for keepLeft and keepRight to be effective. If the input string is shorter than this length, the whole string would be masked. Default value is 3. |
| `maskLengthOrMaskString` | `undefined` \| ``null`` \| `string` \| `number` | `null` | The string to be used for replacing the part in the input that needs to be masked, or the length of the mask string if a fixed length is desired, or null/undefined if the mask string should have the same length as the part to be masked. Default value is null. |
| `maskPattern` | `string` | `'*'` | The pattern to be repeated as the mask. Default value is '*'. |
| `keepLeft` | `number` | `1` | Number of characters on the left to be kept in the output without masking. Default value is 1. |
| `keepRight` | `number` | `0` | Number of characters on the right to be kept in the output without masking. Default value is 0. |
| `minLength` | `number` | `3` | Minimal length of the string for keepLeft and keepRight to be effective. If the input string is shorter than this length, the whole string would be masked. Default value is 3. |
| `maskLengthOrMaskString` | `undefined` \| ``null`` \| `string` \| `number` | `null` | The string to be used for replacing the part in the input that needs to be masked, or the length of the mask string if a fixed length is desired, or null/undefined if the mask string should have the same length as the part to be masked. Default value is null. |
| `maskPattern` | `string` | `'*'` | The pattern to be repeated as the mask. Default value is '*'. |

@@ -665,3 +1014,3 @@ ###### Returns

#### Type aliases
#### Type Aliases

@@ -684,6 +1033,6 @@ ##### PathAwareReplacer

| `value` | `any` | Value of the property or the object in the parent array. |
| `path` | `string` | The full path of the property in the object, such like "access.visitor.location" or "request.x-forwarded-for.0". Please note that the special characters (including ".") in property names are not escaped, for example, "order.billing address.first line". |
| `path` | `string` | The full path of the property in the object, such like "access.visitor.location" or "request.x-forwarded-for.0". Please note that the special characters (including ".") in property names are not escaped, for example, "order.billing address.first line". |
| `parent` | `Parent` | The object that the property or the element belongs to. It could be `{ '': <the original object> }` when this replacer function is called the first time. |
| `pathArray` | `string`[] | The full path as an array. It is more useful than `path` in case special characters exist in property names. When this replacer function is called the first time, pathArray array would have a zero length. |
| `ancestors` | `Parent`[] | All the ancestor objects/arrays of the property. When this replacer function is called the first time, ancestors array would have a zero length. |
| `pathArray` | `string`[] | The full path as an array. It is more useful than `path` in case special characters exist in property names. When this replacer function is called the first time, pathArray array would have a zero length. |
| `ancestors` | `Parent`[] | All the ancestor objects/arrays of the property. When this replacer function is called the first time, ancestors array would have a zero length. |

@@ -707,3 +1056,3 @@ ####### Returns

| `replacer` | [`PathAwareReplacer`](#pathawarereplacer) | The actual replacer function which could utilise additional information. |
| `options?` | `Object` | Options to control whether the pathArray and ancestors parameters would have values populated. By default all information available would be populated. There is no need to specify options unless you are extremely concerned about performance, for example if you need to frequently stringify 500MB objects. |
| `options?` | `Object` | Options to control whether the pathArray and ancestors parameters would have values populated. By default all information available would be populated. There is no need to specify options unless you are extremely concerned about performance, for example if you need to frequently stringify 500MB objects. |
| `options.ancestors?` | `boolean` | - |

@@ -727,5 +1076,5 @@ | `options.pathArray?` | `boolean` | - |

**`example`**
```javascript
**`Example`**
```ts
import { mask, maskAll, maskEmail, maskFullName, pathBasedReplacer } from '@handy-common-utils/misc-utils';

@@ -740,4 +1089,4 @@ console.log(JSON.stringify(obj, pathBasedReplacer([

])));
```
```
###### Parameters

@@ -744,0 +1093,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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