tiny-crypto-suite
Version:
Tiny tools, big crypto โ seamless encryption and certificate handling for modern web and Node apps.
259 lines (182 loc) โข 9.32 kB
Markdown
# ๐ TinyCryptoParser Documentation
`TinyCryptoParser` is a JavaScript utility class that provides robust serialization and deserialization of complex JavaScript data types into JSON-compatible formats.
It ensures data safety for encryption ๐, transmission ๐ก, or storage ๐พ.
---
## โจ Features
- Converts complex data types like `Map`, `Set`, `Buffer`, `Date`, `BigInt`, `Symbol`, and `HTMLElement`.
- Provides strong type validation during deserialization โ
.
- Throws errors for unsupported types like `WeakMap`, `WeakSet`, `Promise`, and `Function` ๐ซ.
- Deep serialization and deserialization support ๐.
---
## ๐ฅ Usage Example
```javascript
import { TinyCryptoParser } from 'tiny-crypto-suite';
const parser = new TinyCryptoParser();
// Serialize a Map
const serialized = parser.serialize(new Map([['key', 'value']]));
// Deserialize it back
const { value, type } = parser.deserialize(serialized);
console.log(value); // Map { 'key' => 'value' }
console.log(type); // 'map'
```
---
## ๐๏ธ Class: `TinyCryptoParser`
### โก๏ธ serialize(data)
๐น Serializes a JavaScript value into a JSON-compatible string.
| Parameter | Type | Description |
|:----------|:-----|:------------|
| `data` | `any` | The data to serialize. |
| Returns | Type | Description |
|:--------|:-----|:------------|
| `string` | `string` | The serialized JSON string. |
โ ๏ธ Throws an error if the data type is unsupported.
---
### โก๏ธ deserialize(text, expectedType = null)
๐น Deserializes a JSON string back to its original JavaScript object.
| Parameter | Type | Description |
|:----------|:-----|:------------|
| `text` | `string` | The serialized string. |
| `expectedType` | `string \| null` | (Optional) Expected type to validate against. |
| Returns | Type | Description |
|:--------|:-----|:------------|
| `DeserializedData` | `{ value: any; type: string }` | The deserialized object and its type. |
โ ๏ธ Throws an error if types mismatch when `expectedType` is provided.
---
### โก๏ธ serializeDeep(data)
๐น Recursively serializes an entire object or array, converting all nested structures.
| Parameter | Type | Description |
|:----------|:-----|:------------|
| `data` | `any` | Data to deeply serialize. |
| Returns | Type | Description |
|:--------|:-----|:------------|
| `string` | `string` | Deeply serialized data. |
---
### โก๏ธ deserializeDeep(text, expectedType = null)
๐น Recursively deserializes a deeply structured JSON string.
| Parameter | Type | Description |
|:----------|:-----|:------------|
| `text` | `string` | The deeply serialized string. |
| `expectedType` | `string \| null` | (Optional) Expected type for validation. |
| Returns | Type | Description |
|:--------|:-----|:------------|
| `DeserializedData` | `{ value: any; type: string }` | The deeply deserialized object. |
---
## ๐งฉ Supported Types
| Type | Serialization | Deserialization |
|:-----|:--------------|:----------------|
| `number` | โ
| โ
|
| `boolean` | โ
| โ
|
| `string` | โ
| โ
|
| `null` | โ
| โ
|
| `undefined` | โ
| โ
|
| `bigint` | โ
| โ
|
| `symbol` | โ
| โ
|
| `map` | โ
| โ
|
| `set` | โ
| โ
|
| `regexp` | โ
| โ
|
| `date` | โ
| โ
|
| `buffer` | โ
| โ
|
| `array` | โ
| โ
|
| `object` | โ
| โ
|
| `htmlElement` | โ
(Browser Only) | โ
(Browser Only) |
| `function`, `promise`, `weakmap`, `weakset` | โ Throws error ๐ซ | N/A |
---
## โ๏ธ Internal Mechanisms
### ๐ ๏ธ `#valueConvertTypes`
- Map of types โ serialization functions.
- Handles type-specific transformations.
### ๐ ๏ธ `#valueTypes`
- Map of types โ deserialization functions.
- Converts JSON-compatible representations back into real JavaScript objects.
### ๐ก๏ธ `#validateDeserializedType(expected, actual)`
- Ensures that deserialized data matches the expected type.
- Throws an error on mismatch.
---
## ๐งน Notes
- Buffer operations depend on Node.js's `Buffer` or browser polyfills.
- Deserialization of `HTMLElement` only works inside browser environments ๐.
- Symbol descriptions are used for serialization; uniqueness is not guaranteed during restoration.
---
### โจ `addValueType` Function Documentation
The `addValueType` function allows you to add new types and their corresponding converter functions to your instance. This function ensures that both the type and the converter are validated as proper functions and that a type name does not already exist in the list. ๐
## Method Signature
```javascript
addValueType(typeName, getFunction, convertFunction, serializeDeep, deserializeDeep)
```
### ๐ Parameters
- **`typeName`** `(string)`:
- The name of the new type you wish to add. ๐ท๏ธ
- This name must be unique within the list of existing types. โ
- **`getFunction`** `(function(data: any) => any)`:
- A function that converts a serialized value back into a value representation. ๐
- This should be used to transform the data into a readable or usable format when needed.
- **`convertFunction`** `(function(data: any) => SerializedData)`:
- A function responsible for serializing the value into a specific structured format. ๐ง
- The serialized value will usually be returned as an object, ensuring you can store it in a consistent way for future conversion.
- **`serializeDeep`** `(function(data: any) => any)` _(optional)_:
- A function that deeply serializes a value type into a JSON-compatible format. ๐๐
- This function is invoked when the data is serialized deeply, meaning if the type is complex (e.g., objects, arrays, or custom types), it will recursively traverse the structure and serialize each element.
- For example, you might use this function to serialize a `Map` or `Set`, ensuring that each key-value pair or set element is serialized deeply.
- **`deserializeDeep`** `(function(data: any) => any)` _(optional)_:
- A function that deeply deserializes a serialized value back to its original format. ๐๐ก
- This function is used to handle cases where you need to recursively parse complex data types (such as objects, arrays, `Map`, or `Set`) back into their original form.
- For example, you might use this function to deserialize a `Map` or `Set`, converting it back into a structure that holds the appropriate data types.
### ๐ Return
- This function does not return anything explicitly. It adds the `typeName`, `getFunction`, `convertFunction`, `serializeDeep`, and `deserializeDeep` to their respective collections (`#valueTypes`, `#valueConvertTypes`, `#deepSerialize`, and `#deepDeserialize`). ๐
### โ ๏ธ Throws
- **`Error`**: If either `getFunction` or `convertFunction` is not a function, an error will be thrown. ๐
- **`Error`**: If either `serializeDeep` or `deserializeDeep` is defined but not a function, an error will be thrown. ๐
- **`Error`**: If the provided `typeName` already exists in the list, an error will be thrown. โ ๏ธ
## ๐งโ๐ป Usage
### ๐ Example 1: Adding a Type for Regular Expressions
```javascript
myInstance.addValueType(
'regexp',
/**
* @param {*} value - The serialized regular expression string.
* @returns {RegExp} The deserialized RegExp object.
*/
(value) => {
const match = value.match(/^\/(.*)\/([gimsuy]*)$/);
return match ? new RegExp(match[1], match[2]) : new RegExp(value);
},
// Convert
(data) => ({ __type: 'regexp', value: data.toString() }),
);
```
### ๐ Example 2: Adding a Type for Array with serialization
```javascript
myInstance.addValueType(
'array',
/**
* @param {*} value - The serialized representation of the array.
* @returns {Array<*>} The deserialized array.
*/
(value) => value,
// Convert
(data) => ({ __type: 'array', value: data }),
// Serialization
(data) => data.map(/** @param {*} item */ (item) => myInstance.serializeDeep(item)),
// Deserialization
(value) => value.map(/** @param {*} item */ (item) => myInstance.deserializeDeep(item).value),
);
```
### ๐จ Error Handling
If you try to add a type with an existing name or if the functions are not provided correctly, the function will throw an error. โ
#### โ ๏ธ Example of Duplicate Type Name
```javascript
myInstance.addValueType('regexp');
// Error: Type "regexp" already exists. ๐ซ
```
#### ๐ Example of Invalid Function Type
```javascript
myInstance.addValueType('number');
// Error: Both getFunction and convertFunction must be functions. โ ๏ธ
```
## ๐ How It Works Internally
- The function first validates whether both `getFunction` and `convertFunction` are indeed functions. โ
- It then checks if the `typeName` already exists in the `#valueTypes` or `#valueConvertTypes` collections. If it does, it throws an error. ๐ซ
- Finally, it adds the new type and its corresponding conversion function to the collections. ๐
## ๐ Important Notes
- **Unique Type Names**: Ensure that the `typeName` you provide does not already exist. If you try to add a type with a name that already exists, an error will be thrown. โ ๏ธ
- **Function Format**: Both the `getFunction` and `convertFunction` must follow the specified formats. The `getFunction` should serialize the value, and the `convertFunction` should convert it back to a usable format. ๐ง