@outburn/format-converter 1.0.1 โ 1.0.4
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.
- package/LICENSE +20 -20
- package/README.md +355 -170
- package/dist/browser/browser.js +2 -0
- package/dist/browser/browser.js.map +1 -0
- package/dist/index.cjs +85 -0
- package/dist/index.d.ts +123 -2
- package/dist/index.mjs +85 -1
- package/package.json +18 -6
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -76
- package/dist/index.mjs.map +0 -1
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Outburn
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Outburn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,171 +1,356 @@
|
|
|
1
|
-
# Format Converter
|
|
2
|
-
|
|
3
|
-
A TypeScript library for converting
|
|
4
|
-
|
|
5
|
-
## Features
|
|
6
|
-
|
|
7
|
-
- ๐ **Multi-format support**: Convert
|
|
8
|
-
- ๐ฅ **Healthcare focused**: Specialized HL7 v2 message parsing and conversion
|
|
9
|
-
- ๐ **Format detection**: Automatic content type detection
|
|
10
|
-
- ๐ก๏ธ **Type-safe**: Written in TypeScript with full type definitions
|
|
11
|
-
- ๐งช **Well-tested**: Comprehensive test suite
|
|
12
|
-
|
|
13
|
-
## Installation
|
|
14
|
-
|
|
15
|
-
```bash
|
|
16
|
-
npm install @outburn/format-converter
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
##
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
###
|
|
50
|
-
|
|
51
|
-
```typescript
|
|
52
|
-
import { FormatConverter } from '@outburn/format-converter';
|
|
53
|
-
|
|
54
|
-
const converter = new FormatConverter();
|
|
55
|
-
|
|
56
|
-
// Convert
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
1
|
+
# Format Converter
|
|
2
|
+
|
|
3
|
+
A TypeScript library for converting various data formats (CSV, XML, HL7 v2) to JSON.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- ๐ **Multi-format support**: Convert CSV, XML, HL7 v2 to JSON
|
|
8
|
+
- ๐ฅ **Healthcare focused**: Specialized HL7 v2 message parsing and conversion to JSON
|
|
9
|
+
- ๐ **Format detection**: Automatic content type detection
|
|
10
|
+
- ๐ก๏ธ **Type-safe**: Written in TypeScript with full type definitions
|
|
11
|
+
- ๐งช **Well-tested**: Comprehensive test suite
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @outburn/format-converter
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Browser Compatibility
|
|
20
|
+
|
|
21
|
+
This library provides different builds for different environments:
|
|
22
|
+
|
|
23
|
+
### Node.js (Full functionality)
|
|
24
|
+
```typescript
|
|
25
|
+
import { FormatConverter, TypeConverter, FormatDetector } from '@outburn/format-converter';
|
|
26
|
+
// All features available including HL7 v2 conversion
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Browser (Limited functionality)
|
|
30
|
+
```html
|
|
31
|
+
<script src="node_modules/@outburn/format-converter/dist/browser/browser.js"></script>
|
|
32
|
+
<script>
|
|
33
|
+
const { TypeConverter, FormatDetector } = FormatUtils;
|
|
34
|
+
// FormatConverter is not available in browser due to HL7.js dependency
|
|
35
|
+
</script>
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**Browser limitations:**
|
|
39
|
+
- โ `FormatConverter` is not available (requires HL7.js which is not browser-compatible)
|
|
40
|
+
- โ HL7 v2 parsing and conversion
|
|
41
|
+
- โ
`TypeConverter` for type detection and conversion
|
|
42
|
+
- โ
`FormatDetector` for format detection (JSON, XML, CSV, HL7)
|
|
43
|
+
- โ
All type definitions and enums
|
|
44
|
+
|
|
45
|
+
For full functionality including HL7 processing, use the Node.js version.
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
### Basic Usage
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { FormatConverter } from '@outburn/format-converter';
|
|
53
|
+
|
|
54
|
+
const converter = new FormatConverter();
|
|
55
|
+
|
|
56
|
+
// Convert CSV to JSON
|
|
57
|
+
const csvData = `name,age,city
|
|
58
|
+
John,25,New York
|
|
59
|
+
Jane,30,Los Angeles`;
|
|
60
|
+
|
|
61
|
+
const jsonResult = await converter.toJson(csvData, 'text/csv');
|
|
62
|
+
console.log(jsonResult);
|
|
63
|
+
|
|
64
|
+
// Convert XML to JSON
|
|
65
|
+
const xmlData = `<?xml version="1.0"?>
|
|
66
|
+
<root>
|
|
67
|
+
<person>
|
|
68
|
+
<name>John</name>
|
|
69
|
+
<age>25</age>
|
|
70
|
+
</person>
|
|
71
|
+
</root>`;
|
|
72
|
+
|
|
73
|
+
const xmlToJson = await converter.toJson(xmlData, 'application/xml');
|
|
74
|
+
console.log(xmlToJson);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### HL7 v2 Message Conversion
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { FormatConverter } from '@outburn/format-converter';
|
|
81
|
+
|
|
82
|
+
const converter = new FormatConverter();
|
|
83
|
+
|
|
84
|
+
// Convert HL7 v2 message to JSON
|
|
85
|
+
const hl7Message = `MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4
|
|
86
|
+
PID|||PATID1234^5^M11^ADT1^MR^UNIVERSITY HOSPITAL~123456789^^^USSSA^SS||EVERYMAN^ADAM^A^III||19610615|M||C|1200 N ELM STREET^^GREENSBORO^NC^27401-1020|GL|(919)379-1212|(919)271-3434||S||PATID12345001^2^M10^ADT1^AN^A|123456789|9-87654^NC`;
|
|
87
|
+
|
|
88
|
+
const hl7ToJson = await converter.toJson(hl7Message, 'x-application/hl7-v2+er7');
|
|
89
|
+
console.log(hl7ToJson);
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### With Logging
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
import { FormatConverter } from '@outburn/format-converter';
|
|
96
|
+
|
|
97
|
+
// Custom logger implementation
|
|
98
|
+
const logger = {
|
|
99
|
+
info: (message: string) => console.log(`[INFO] ${message}`),
|
|
100
|
+
warn: (message: string) => console.warn(`[WARN] ${message}`),
|
|
101
|
+
error: (message: string) => console.error(`[ERROR] ${message}`)
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const converter = new FormatConverter(logger);
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Type Conversion Utilities
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { TypeConverter } from '@outburn/format-converter';
|
|
111
|
+
|
|
112
|
+
const typeConverter = new TypeConverter();
|
|
113
|
+
|
|
114
|
+
// Convert MIME type strings to ContentType enum
|
|
115
|
+
const contentType = typeConverter.stringToContentType('text/csv');
|
|
116
|
+
|
|
117
|
+
// Detect format from content
|
|
118
|
+
const detectedFormat = typeConverter.detectFormat(csvData);
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Supported Formats
|
|
122
|
+
|
|
123
|
+
This library converts the following input formats to JSON:
|
|
124
|
+
|
|
125
|
+
| Input Format | Content Type | Output |
|
|
126
|
+
|--------------|--------------|--------|
|
|
127
|
+
| CSV | `text/csv` | JSON |
|
|
128
|
+
| XML | `application/xml` | JSON |
|
|
129
|
+
| HL7 v2 | `x-application/hl7-v2+er7` | JSON |
|
|
130
|
+
| JSON | `application/json` | JSON (passthrough) |
|
|
131
|
+
|
|
132
|
+
## API Reference
|
|
133
|
+
|
|
134
|
+
### FormatConverter
|
|
135
|
+
|
|
136
|
+
The main class for converting various formats to JSON.
|
|
137
|
+
|
|
138
|
+
#### Constructor
|
|
139
|
+
```typescript
|
|
140
|
+
new FormatConverter(logger?: ILogger)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
**Parameters:**
|
|
144
|
+
- `logger` (optional): Custom logger implementing the `ILogger` interface
|
|
145
|
+
|
|
146
|
+
#### Methods
|
|
147
|
+
|
|
148
|
+
##### `toJson(input: any, contentType?: ContentType | string): Promise<any>`
|
|
149
|
+
|
|
150
|
+
Converts input data to JSON format. This is the primary method for format conversion.
|
|
151
|
+
|
|
152
|
+
**Parameters:**
|
|
153
|
+
- `input`: The data to convert (string or object)
|
|
154
|
+
- `contentType` (optional): The MIME type or ContentType enum value of the input data. If not provided, defaults to `application/json`
|
|
155
|
+
|
|
156
|
+
**Returns:** Promise resolving to the converted JSON data
|
|
157
|
+
|
|
158
|
+
**Example:**
|
|
159
|
+
```typescript
|
|
160
|
+
const result = await converter.toJson(csvData, 'text/csv');
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
##### `csvToJson(input: string): Promise<any>`
|
|
164
|
+
|
|
165
|
+
Converts CSV data to JSON format.
|
|
166
|
+
|
|
167
|
+
**Parameters:**
|
|
168
|
+
- `input`: CSV string to convert
|
|
169
|
+
|
|
170
|
+
**Returns:** Promise resolving to the converted JSON data
|
|
171
|
+
|
|
172
|
+
##### `xmlToJson(input: string): Promise<any>`
|
|
173
|
+
|
|
174
|
+
Converts XML data to JSON format.
|
|
175
|
+
|
|
176
|
+
**Parameters:**
|
|
177
|
+
- `input`: XML string to convert
|
|
178
|
+
|
|
179
|
+
**Returns:** Promise resolving to the converted JSON data
|
|
180
|
+
|
|
181
|
+
##### `hl7v2ToJson(input: string): Promise<any>`
|
|
182
|
+
|
|
183
|
+
Converts HL7 v2 message to JSON format.
|
|
184
|
+
|
|
185
|
+
**Parameters:**
|
|
186
|
+
- `input`: HL7 v2 message string to convert
|
|
187
|
+
|
|
188
|
+
**Returns:** Promise resolving to the converted JSON data
|
|
189
|
+
|
|
190
|
+
### TypeConverter
|
|
191
|
+
|
|
192
|
+
Utility class for converting between different content type representations.
|
|
193
|
+
|
|
194
|
+
#### Methods
|
|
195
|
+
|
|
196
|
+
##### `stringToContentType(contentType: string): ContentType | null`
|
|
197
|
+
|
|
198
|
+
Converts a MIME type string to a ContentType enum value.
|
|
199
|
+
|
|
200
|
+
**Parameters:**
|
|
201
|
+
- `contentType`: MIME type string (e.g., 'text/csv', 'application/xml')
|
|
202
|
+
|
|
203
|
+
**Returns:** ContentType enum value or null if not found
|
|
204
|
+
|
|
205
|
+
**Example:**
|
|
206
|
+
```typescript
|
|
207
|
+
const contentType = typeConverter.stringToContentType('text/csv');
|
|
208
|
+
// Returns: ContentType.CSV
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
##### `stringToContentFormat(format: string): ContentFormat | null`
|
|
212
|
+
|
|
213
|
+
Converts a format string to a ContentFormat enum value.
|
|
214
|
+
|
|
215
|
+
**Parameters:**
|
|
216
|
+
- `format`: Format string (e.g., 'json', 'csv', 'xml', 'hl7')
|
|
217
|
+
|
|
218
|
+
**Returns:** ContentFormat enum value or null if not found
|
|
219
|
+
|
|
220
|
+
##### `stringToEditorLanguage(editorLanguage: string): EditorLanguage | null`
|
|
221
|
+
|
|
222
|
+
Converts a language string to an EditorLanguage enum value.
|
|
223
|
+
|
|
224
|
+
**Parameters:**
|
|
225
|
+
- `editorLanguage`: Editor language string (e.g., 'json', 'xml', 'plaintext')
|
|
226
|
+
|
|
227
|
+
**Returns:** EditorLanguage enum value or null if not found
|
|
228
|
+
|
|
229
|
+
##### `contentTypeToContentFormat(contentType: ContentType): ContentFormat`
|
|
230
|
+
|
|
231
|
+
Converts a ContentType enum to a ContentFormat enum.
|
|
232
|
+
|
|
233
|
+
**Parameters:**
|
|
234
|
+
- `contentType`: ContentType enum value
|
|
235
|
+
|
|
236
|
+
**Returns:** Corresponding ContentFormat enum value
|
|
237
|
+
|
|
238
|
+
##### `contentTypeToEditorLanguage(contentType: ContentType): EditorLanguage`
|
|
239
|
+
|
|
240
|
+
Converts a ContentType enum to an EditorLanguage enum.
|
|
241
|
+
|
|
242
|
+
**Parameters:**
|
|
243
|
+
- `contentType`: ContentType enum value
|
|
244
|
+
|
|
245
|
+
**Returns:** Corresponding EditorLanguage enum value
|
|
246
|
+
|
|
247
|
+
##### `contentFormatToContentType(format: ContentFormat): ContentType | null`
|
|
248
|
+
|
|
249
|
+
Converts a ContentFormat enum to a ContentType enum.
|
|
250
|
+
|
|
251
|
+
**Parameters:**
|
|
252
|
+
- `format`: ContentFormat enum value
|
|
253
|
+
|
|
254
|
+
**Returns:** Corresponding ContentType enum value or null if not applicable
|
|
255
|
+
|
|
256
|
+
##### `contentFormatToEditorLanguage(format: ContentFormat): EditorLanguage`
|
|
257
|
+
|
|
258
|
+
Converts a ContentFormat enum to an EditorLanguage enum.
|
|
259
|
+
|
|
260
|
+
**Parameters:**
|
|
261
|
+
- `format`: ContentFormat enum value
|
|
262
|
+
|
|
263
|
+
**Returns:** Corresponding EditorLanguage enum value
|
|
264
|
+
|
|
265
|
+
### FormatDetector
|
|
266
|
+
|
|
267
|
+
Utility class for automatically detecting content formats from input strings.
|
|
268
|
+
|
|
269
|
+
#### Methods
|
|
270
|
+
|
|
271
|
+
##### `detectContentType(input: string): ContentType | null`
|
|
272
|
+
|
|
273
|
+
Detects the content type of the input string and returns the corresponding ContentType enum.
|
|
274
|
+
|
|
275
|
+
**Parameters:**
|
|
276
|
+
- `input`: String content to analyze
|
|
277
|
+
|
|
278
|
+
**Returns:** ContentType enum value or null if format cannot be determined
|
|
279
|
+
|
|
280
|
+
**Example:**
|
|
281
|
+
```typescript
|
|
282
|
+
const detector = new FormatDetector();
|
|
283
|
+
const contentType = detector.detectContentType(csvData);
|
|
284
|
+
// Returns: ContentType.CSV
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
##### `detectFormat(input: string): ContentFormat`
|
|
288
|
+
|
|
289
|
+
Analyzes the input string and detects its format.
|
|
290
|
+
|
|
291
|
+
**Parameters:**
|
|
292
|
+
- `input`: String content to analyze
|
|
293
|
+
|
|
294
|
+
**Returns:** ContentFormat enum value (returns ContentFormat.UNKNOWN if format cannot be determined)
|
|
295
|
+
|
|
296
|
+
**Example:**
|
|
297
|
+
```typescript
|
|
298
|
+
const detector = new FormatDetector();
|
|
299
|
+
const format = detector.detectFormat(xmlData);
|
|
300
|
+
// Returns: ContentFormat.XML
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
##### `detectEditorLanguage(input: string): EditorLanguage`
|
|
304
|
+
|
|
305
|
+
Detects the appropriate editor language syntax highlighting for the input content.
|
|
306
|
+
|
|
307
|
+
**Parameters:**
|
|
308
|
+
- `input`: String content to analyze
|
|
309
|
+
|
|
310
|
+
**Returns:** EditorLanguage enum value
|
|
311
|
+
|
|
312
|
+
**Example:**
|
|
313
|
+
```typescript
|
|
314
|
+
const detector = new FormatDetector();
|
|
315
|
+
const language = detector.detectEditorLanguage(jsonData);
|
|
316
|
+
// Returns: EditorLanguage.JSON
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## Development
|
|
320
|
+
|
|
321
|
+
### Building
|
|
322
|
+
|
|
323
|
+
```bash
|
|
324
|
+
npm run build
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
### Testing
|
|
328
|
+
|
|
329
|
+
```bash
|
|
330
|
+
npm test
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
### Linting
|
|
334
|
+
|
|
335
|
+
```bash
|
|
336
|
+
npm run lint
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
## Dependencies
|
|
340
|
+
|
|
341
|
+
- **csvtojson**: CSV parsing functionality
|
|
342
|
+
- **fast-xml-parser**: XML parsing and conversion
|
|
343
|
+
- **hl7-dictionary**: HL7 v2 message definitions
|
|
344
|
+
- **hl7js**: HL7 message parsing utilities
|
|
345
|
+
- **jsonata**: JSON transformation and querying
|
|
346
|
+
|
|
347
|
+
## License
|
|
348
|
+
MIT
|
|
349
|
+
ยฉ Outburn Ltd. 2022โ2025. All Rights Reserved.
|
|
350
|
+
|
|
351
|
+
## Disclaimer
|
|
352
|
+
This project is part of the [FUME](https://github.com/Outburn-IL/fume-community) open-source initiative and intended for use in FHIR tooling and development environments.
|
|
353
|
+
|
|
354
|
+
## Support
|
|
355
|
+
|
|
171
356
|
For issues and questions, please use the [GitHub Issues](https://github.com/Outburn-IL/format-converter/issues) page.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var FormatUtils=(function(exports){'use strict';var i=(a=>(a.JSON="application/json",a.CSV="text/csv",a.XML="application/xml",a.HL7V2="x-application/hl7-v2+er7",a))(i||{});var c=(s=>(s.JSON="json",s.CSV="csv",s.XML="xml",s.HL7="hl7",s.UNKNOWN="unknown",s))(c||{});var m=(o=>(o.JSON="json",o.XML="xml",o.PLAINTEXT="plaintext",o))(m||{});var r=class r{contentTypeToContentFormat(t){return r.contentTypeToContentFormatMap[t]}contentTypeToEditorLanguage(t){let e=this.contentTypeToContentFormat(t);return this.contentFormatToEditorLanguage(e)}contentFormatToContentType(t){return r.contentFormatToContentTypeMap[t]||null}contentFormatToEditorLanguage(t){return r.contentFormatToEditorLanguageMap[t]}stringToContentFormat(t){let e=t.toLowerCase();return r.contentFormats.find(o=>o===e)||null}stringToContentType(t){let e=t.toLowerCase();return r.contentTypes.find(o=>e.startsWith(o))||null}stringToEditorLanguage(t){let e=t.toLowerCase();return r.editorLanguages.find(o=>o===e)||null}};r.contentTypeToContentFormatMap={"application/json":"json","text/csv":"csv","application/xml":"xml","x-application/hl7-v2+er7":"hl7"},r.contentFormatToContentTypeMap={json:"application/json",csv:"text/csv",xml:"application/xml",hl7:"x-application/hl7-v2+er7",unknown:null},r.contentFormatToEditorLanguageMap={json:"json",xml:"xml",csv:"plaintext",hl7:"plaintext",unknown:"plaintext"},r.contentFormats=["json","csv","xml","hl7","unknown"],r.contentTypes=["application/json","text/csv","application/xml","x-application/hl7-v2+er7"],r.editorLanguages=["json","xml","plaintext"];var l=r;var L=n=>typeof n=="string"&&n.trimStart().startsWith("MSH|"),T=n=>{try{return JSON.parse(n),!0}catch(t){return false}},C=n=>{let t=n,e={curlyBraces:(t.match(/[{}]/g)||[]).length,colons:(t.match(/:/g)||[]).length,keyValueStructure:/{[^}]*:[^}]*}/.test(n)},o=/{[^}]*"[^"]*"\s*:\s*/.test(n);return (e.curlyBraces>=2||e.curlyBraces>=1&&o)&&e.colons>=1&&(e.keyValueStructure||/{.*:.*}/.test(n)||o)},y=n=>{let t={openingTags:(n.match(/<[^/!?][^>]*?>/g)||[]).length,closingTags:(n.match(/<\/[^>]+>/g)||[]).length,selfClosingTags:(n.match(/<[^>]+\/>/g)||[]).length,xmlNamespaces:(n.match(/xmlns(:[a-zA-Z0-9]+)?=/g)||[]).length};return (/^<\?xml.*?\?>/.test(n)||t.xmlNamespaces>=1||t.openingTags>=1)&&(t.openingTags===t.closingTags||t.selfClosingTags>=1)},N=n=>{let t=n.split(/\r?\n/),e=t[0],o={rowCount:t.length,commaCounts:t.map(p=>(p.match(/,/g)||[]).length)},a={curlyBraces:(e.match(/[{}]/g)||[]).length,squareBrackets:(e.match(/[\[\]]/g)||[]).length,angularBrackets:(e.match(/[<>]/g)||[]).length,colons:(e.match(/:/g)||[]).length};return (o.rowCount>1||o.commaCounts.some(p=>p>0))&&a.curlyBraces===0&&a.squareBrackets===0&&a.angularBrackets===0&&a.colons===0},g=class g{detectContentType(t){let e=this.detectFormat(t);return g.typeConverter.contentFormatToContentType(e)}detectFormat(t){try{return (t==null?void 0:t.trim())?T(t)?"json":L(t)?"hl7":C(t)?"json":y(t)?"xml":N(t)?"csv":"unknown":"unknown"}catch(e){return "unknown"}}detectEditorLanguage(t){switch(this.detectFormat(t)){case "json":return "json";case "xml":return "xml";default:return "plaintext"}}};g.typeConverter=new l;var u=g;exports.ContentFormat=c;exports.ContentType=i;exports.EditorLanguage=m;exports.FormatDetector=u;exports.TypeConverter=l;return exports;})({});//# sourceMappingURL=browser.js.map
|
|
2
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/types/ContentType.ts","../../src/types/ContentFormat.ts","../../src/types/EditorLanguage.ts","../../src/TypeConverter.ts","../../src/FormatDetector.ts"],"names":["ContentType","ContentFormat","EditorLanguage","_TypeConverter","contentType","format","normalizedFormat","value","normalizedContentType","editorLanguage","normalizedLanguage","TypeConverter","isPossiblyHL7","input","isValidJson","e","isJsonLikely","inputWithoutStrings","jsonStats","hasIncompleteJsonPattern","isXmlLikely","xmlStats","isCsvLikely","lines","headerRow","csvStats","line","headerStats","count","_FormatDetector","FormatDetector"],"mappings":"gDAKO,IAAWA,CAAAA,CAAAA,CAAAA,CAAAA,GAEdA,CAAAA,CAAA,IAAA,CAAO,kBAAA,CAEPA,CAAAA,CAAA,GAAA,CAAM,UAAA,CAENA,CAAAA,CAAA,GAAA,CAAM,i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AC5BA,CAAAA,CAAY,cAAA,GAAmB,CAAA,EAC/BA,CAAAA,CAAY,eAAA,GAAoB,CAAA,EAChCA,CAAAA,CAAY,MAAA,GAAW,CAG3B,CAAA,CAEaE,CAAAA,CAAN,MAAMA,CAA0C,CAGrD,iBAAA,CAAkBhB,CAAAA,CAAmC,CACnD,IAAMR,CAAAA,CAAS,IAAA,CAAK,YAAA,CAAaQ,CAAK,CAAA,CACtC,OAAOgB,CAAAA,CAAe,aAAA,CAAc,0BAAA,CAA2BxB,CAAM,CACvE,CAEA,YAAA,CAAaQ,CAAAA,CAA8B,CACzC,GAAI,CAEF,OAAA,CADqBA,CAAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAAA,CAAO,IAAA,EAAA,EAExBC,CAAAA,CAAYD,CAAK,CAAA,CAAA,MAAA,CACjBD,CAAAA,CAAcC,CAAK,CAAA,CAAA,KAAA,CACnBG,CAAAA,CAAaH,CAAK,CAAA,CAAA,MAAA,CAClBO,CAAAA,CAAYP,CAAK,CAAA,CAAA,KAAA,CACjBS,CAAAA,CAAYT,CAAK,CAAA,CAAA,KAAA,CAAA,SAAA,CAAA,SAEvB,CAAA,MAAS,CAAA,CAAG,CACV,OAAA,SACF,CACF,CAEA,oBAAA,CAAqBA,CAAAA,CAA+B,CAElD,OADe,IAAA,CAAK,YAAA,CAAaA,CAAK,CAAA,EAEpC,KAAA,MAAA,CACE,OAAA,MAAA,CACF,KAAA,KAAA,CACE,OAAA,KAAA,CACF,QACE,OAAA,WACJ,CACF,CACF,CAAA,CAlCagB,CAAAA,CACa,aAAA,CAAgC,IAAIlB,CAAAA,CADvD,IAAMmB,CAAAA,CAAND","file":"browser.js","sourcesContent":["/**\n * Enumeration of supported MIME types/content types for data format identification.\n * These values correspond to standard HTTP Content-Type header values and are used\n * for format detection and conversion operations.\n */\nexport const enum ContentType {\n /** Standard MIME type for JSON data */\n JSON = 'application/json',\n /** Standard MIME type for CSV data */\n CSV = 'text/csv',\n /** Standard MIME type for XML data */\n XML = 'application/xml',\n /** Custom MIME type for HL7 Version 2.x messages in ER7 encoding */\n HL7V2 = 'x-application/hl7-v2+er7'\n}","/**\n * Enumeration of supported content formats for detection and conversion.\n * Used by format detection algorithms to categorize input data and determine\n * appropriate conversion strategies.\n */\nexport const enum ContentFormat {\n /** JavaScript Object Notation format */\n JSON = 'json',\n /** Comma-Separated Values format */\n CSV = 'csv',\n /** eXtensible Markup Language format */\n XML = 'xml',\n /** Health Level 7 Version 2.x message format */\n HL7 = 'hl7',\n /** Unknown or unsupported format */\n UNKNOWN = 'unknown'\n}","/**\n * Enumeration of supported editor language identifiers for syntax highlighting and editor configuration.\n * These values are used to determine the appropriate language mode for displaying content\n * in code editors or other text editing interfaces.\n */\nexport const enum EditorLanguage {\n /** JSON language mode for syntax highlighting */\n JSON = 'json',\n /** XML language mode for syntax highlighting */\n XML = 'xml',\n /** Plain text mode with no syntax highlighting */\n PLAINTEXT = 'plaintext'\n}","import { ContentFormat, ContentType, EditorLanguage, ITypeConverter } from './types';\n\nexport class TypeConverter implements ITypeConverter {\n private static contentTypeToContentFormatMap: { [key in ContentType]: ContentFormat } = {\n [ContentType.JSON]: ContentFormat.JSON,\n [ContentType.CSV]: ContentFormat.CSV,\n [ContentType.XML]: ContentFormat.XML,\n [ContentType.HL7V2]: ContentFormat.HL7\n };\n\n private static contentFormatToContentTypeMap: { [key in ContentFormat]: ContentType | null } = {\n [ContentFormat.JSON]: ContentType.JSON,\n [ContentFormat.CSV]: ContentType.CSV,\n [ContentFormat.XML]: ContentType.XML,\n [ContentFormat.HL7]: ContentType.HL7V2,\n [ContentFormat.UNKNOWN]: null\n };\n\n private static contentFormatToEditorLanguageMap: { [key in ContentFormat]: EditorLanguage } = {\n [ContentFormat.JSON]: EditorLanguage.JSON,\n [ContentFormat.XML]: EditorLanguage.XML,\n [ContentFormat.CSV]: EditorLanguage.PLAINTEXT,\n [ContentFormat.HL7]: EditorLanguage.PLAINTEXT,\n [ContentFormat.UNKNOWN]: EditorLanguage.PLAINTEXT\n };\n\n private static contentFormats: ContentFormat[] = [\n ContentFormat.JSON,\n ContentFormat.CSV,\n ContentFormat.XML,\n ContentFormat.HL7,\n ContentFormat.UNKNOWN\n ];\n\n private static contentTypes: ContentType[] = [\n ContentType.JSON,\n ContentType.CSV,\n ContentType.XML,\n ContentType.HL7V2\n ];\n\n private static editorLanguages: EditorLanguage[] = [\n EditorLanguage.JSON,\n EditorLanguage.XML,\n EditorLanguage.PLAINTEXT\n ];\n\n contentTypeToContentFormat(contentType: ContentType): ContentFormat {\n return TypeConverter.contentTypeToContentFormatMap[contentType];\n }\n\n contentTypeToEditorLanguage(contentType: ContentType): EditorLanguage {\n const format = this.contentTypeToContentFormat(contentType);\n return this.contentFormatToEditorLanguage(format);\n }\n\n contentFormatToContentType(format: ContentFormat): ContentType | null {\n return TypeConverter.contentFormatToContentTypeMap[format] || null;\n }\n\n contentFormatToEditorLanguage(format: ContentFormat): EditorLanguage {\n return TypeConverter.contentFormatToEditorLanguageMap[format];\n }\n\n stringToContentFormat(format: string): ContentFormat | null {\n const normalizedFormat = format.toLowerCase();\n return TypeConverter.contentFormats.find(value => value === normalizedFormat) || null;\n }\n\n stringToContentType(contentType: string): ContentType | null {\n const normalizedContentType = contentType.toLowerCase();\n return TypeConverter.contentTypes.find(value => normalizedContentType.startsWith(value)) || null;\n }\n\n stringToEditorLanguage(editorLanguage: string): EditorLanguage | null {\n const normalizedLanguage = editorLanguage.toLowerCase();\n return TypeConverter.editorLanguages.find(value => value === normalizedLanguage) || null;\n }\n\n}","import { TypeConverter } from './TypeConverter';\nimport { ContentFormat, ContentType, EditorLanguage, IFormatDetector, ITypeConverter } from './types';\n\nconst isPossiblyHL7 = (input: string): boolean =>\n typeof input === 'string' && input.trimStart().startsWith('MSH|');\n\nconst isValidJson = (input: string): boolean => {\n try {\n JSON.parse(input);\n return true;\n } catch (e) {\n return false;\n }\n};\n\nconst isJsonLikely = (input: string): boolean => {\n // Remove string values for JSON-specific heuristics (optimized regex)\n const inputWithoutStrings = input; //.replace(/\"[^\"]*\"/g, '\"\"');\n /*\n // Remove string values for JSON-specific heuristics (safe regex to prevent ReDoS)\n const inputWithoutStrings = input.replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"');\n */\n\n const jsonStats = {\n curlyBraces: (inputWithoutStrings.match(/[{}]/g) || []).length,\n colons: (inputWithoutStrings.match(/:/g) || []).length,\n embeddedXml: /<[^>]+>/.test(input),\n keyValueStructure: /{[^}]*:[^}]*}/.test(input), // Key-value pattern\n };\n\n // Check for incomplete JSON patterns (like {\"key\": incomplete)\n const hasIncompleteJsonPattern = /{[^}]*\"[^\"]*\"\\s*:\\s*/.test(input);\n\n const isJsonLikely =\n (jsonStats.curlyBraces >= 2 || (jsonStats.curlyBraces >= 1 && hasIncompleteJsonPattern)) &&\n jsonStats.colons >= 1 &&\n (jsonStats.keyValueStructure || /{.*:.*}/.test(input) || hasIncompleteJsonPattern); // Strong JSON indicators\n\n return isJsonLikely;\n};\n\nconst isXmlLikely = (input: string): boolean => {\n const xmlStats = {\n openingTags: (input.match(/<[^/!?][^>]*?>/g) || []).length,\n closingTags: (input.match(/<\\/[^>]+>/g) || []).length,\n selfClosingTags: (input.match(/<[^>]+\\/>/g) || []).length,\n xmlNamespaces: (input.match(/xmlns(:[a-zA-Z0-9]+)?=/g) || []).length,\n };\n\n const hasXmlHeader = /^<\\?xml.*?\\?>/.test(input);\n const isXmlLikely =\n (hasXmlHeader || xmlStats.xmlNamespaces >= 1 || xmlStats.openingTags >= 1) &&\n (xmlStats.openingTags === xmlStats.closingTags || xmlStats.selfClosingTags >= 1);\n\n return isXmlLikely;\n};\n\nconst isCsvLikely = (input: string): boolean => {\n const lines = input.split(/\\r?\\n/);\n const headerRow = lines[0];\n const csvStats = {\n rowCount: lines.length,\n commaCounts: lines.map(line => (line.match(/,/g) || []).length),\n };\n\n const headerStats = {\n curlyBraces: (headerRow.match(/[{}]/g) || []).length,\n squareBrackets: (headerRow.match(/[\\[\\]]/g) || []).length,\n angularBrackets: (headerRow.match(/[<>]/g) || []).length,\n colons: (headerRow.match(/:/g) || []).length,\n };\n\n const isCsvLikely =\n (csvStats.rowCount > 1 || csvStats.commaCounts.some(count => count > 0)) &&\n headerStats.curlyBraces === 0 &&\n headerStats.squareBrackets === 0 &&\n headerStats.angularBrackets === 0 &&\n headerStats.colons === 0;\n\n return isCsvLikely;\n};\n\nexport class FormatDetector implements IFormatDetector {\n private static readonly typeConverter: ITypeConverter = new TypeConverter();\n\n detectContentType(input: string): ContentType | null {\n const format = this.detectFormat(input);\n return FormatDetector.typeConverter.contentFormatToContentType(format);\n }\n\n detectFormat(input: string): ContentFormat {\n try {\n const trimmedInput = input?.trim();\n if (!trimmedInput) return ContentFormat.UNKNOWN;\n if (isValidJson(input)) return ContentFormat.JSON;\n if (isPossiblyHL7(input)) return ContentFormat.HL7;\n if (isJsonLikely(input)) return ContentFormat.JSON;\n if (isXmlLikely(input)) return ContentFormat.XML;\n if (isCsvLikely(input)) return ContentFormat.CSV;\n return ContentFormat.UNKNOWN;\n } catch (e) {\n return ContentFormat.UNKNOWN;\n }\n }\n\n detectEditorLanguage(input: string): EditorLanguage {\n const format = this.detectFormat(input);\n switch (format) {\n case ContentFormat.JSON:\n return EditorLanguage.JSON;\n case ContentFormat.XML:\n return EditorLanguage.XML;\n default:\n return EditorLanguage.PLAINTEXT;\n }\n }\n}"]}
|